boost::python: howto call a function that expects a pointer? -
i have function takes int-pointer , exposed via boost::python. how can call function python?
in c++ boost::python:
void foo(int* i); ... def("foo", foo);
in python:
import foo_ext = 12 foo_ext.foo(i)
results in
traceback (most recent call last): file "<stdin>", line 1, in <module> boost.python.argumenterror: python argument types in foo(int) did not match c++ signature: foo(int* i)
so how pass pointer?
short answer is: can't. python not have pointers
long answer is: there assorted workarounds depending on use-case.
i notice using int , int* in example. int (along float, str, , bool) special case because immutable in python.
lets object passing in not int.
have wrapper function takes argument reference, takes address , passes on actual function. work seamlessly in python.
ok, int. have problem. can not change int passed in. if try same solution, boost::python complain l-values @ runtime. there still several options.
let's not need see int looks after function exits , know function not squirrel away pointer dereference after function returns:
your wrapper should take int value or const reference. else same.
maybe need see after state (the int out perimeter):
your wrapper function take no arguments, , pass address of local int actual function. return value. if function has return value should return tuple.
both input , output important , know function not squirrel away pointer dereference after function returns:
combine 2 above. wrapper takes 1 int value , returns different int.
the function expects squirrel away pointer dereference after function returns:
there no real solution. can create , expose object in c++ contains c++ int. wrapper take object reference, extract address of contained int , pass on actual function. keeping object alive in python (and safe garbage collector) until library done python writer's problem, , if goofs data corrupt or interpretor crashes.
Comments
Post a Comment