[C++-sig] pass function pointer to c extension function in python

Stefan Seefeld seefeld at sympatico.ca
Wed Oct 4 16:37:40 CEST 2006


Qinfeng(Javen) Shi wrote:
> Dear All,
> 
> I used a global function pointer op, so that when op = add, it operates as
> add, when op = minus, it operates as minus. I used a function
> choose_op() to
> set op = add or minus. It works if I call choose_op() inside other function
> exposed in python. It reported a error when I used bjam to compile it if I
> exposed it into python.
> 
> Any suggestion will be appreciated. Thanks in advance.

In python 'callables' are first-class objects; you can pass them around much
as you can pass around C++ function pointers. There is no reason to export
a 'choose_op' function from C++, as you can 'choose' (assign) a function directly
inside python:

> ---------------------------c extension---------------------
> float add(float a, float b){
>    return a+b;
> }
> float minus(float a, float b){
>    return a-b;
> }
> float (*op)(float a, float b) = add;
> void choose_op(float (* method)(float a, float b)){
>    op = method;
> }
> int funcPtrTest()
> {
>    float a,b,c;
>    a = 1;
>    b = 2;
>    c = -10;
> 
>    choose_op(minus);
>    c = op(a,b);
>    printf("%f\n",c);
>   return 0;
> }
> 
> BOOST_PYTHON_MODULE(hello){
> def("funcPtrTest", &funcPtrTest);
> def("choose_op",&choose_op);// this line makes bjam report an error.
> Without
> it is ok. But without it also means we can't call it directly in python.
> }

Make that:

def("plus", plus);
def("minus", minus);

> ------------------------result-------------
> (1)if without def("choose_op",&choose_op),
>>>> import hello
>>>> c = hello.funcPtrTest()
> -1.000000
> so it works.
> 
> (2)if with def("choose_op",&choose_op),
> It can't be compiled successfully by bjam.
> /boost_1_33_1/boost/type_traits/add_cv.hpp:34: error: `const
>   volatile' qualifiers cannot be applied to `float ()(float, float)'
> 

...and this:

import hello
op = hello.plus
op(1, 2)
op = hello.minus
op(1, 2)


Or did I misunderstand what you are trying to do ?

HTH,
		Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list