retrieve C++object member pointer using Python
I'm using box2d in my application. It has a class b2Body
. It has a property void *userData
and methods for it's accessing. In other words: we can store there some additional info about physic body. I want to store there some class object:
MyClass *obj = new MyClass();
b2Body body;
body.SetUserData(obj);
Now I have to get user data inside python! I wrote a function-wrapper which returns the extracted po开发者_如何学Cinter:
MyClass *GetBodyUserData(b2Body &body)
{
void *userData = body.GetUserData();
if (userData) return (MyClass*)userData;
std::cout << "Fail.";
return nullptr;
}
Now, when I call GetBodyUserData
in python I have an empty or 'dead' object :(.
I tried to store smart pointer insted of pure one but It's not allowed by SetUserData
interface.
Any ideas?
upd Exporting to python:
bp::def("GetBodyUserData", &GetBodyUserData, boost::python::return_value_policy <boost::python::reference_existing_object>())
You just have to do it C-style, i.e. pass the pointer to a function with returns the specific item you want. C++ objects aren't the same as python objects.
Also Python doesn't even have the definition of your c++ object, so even if they looked the same in memory, python could use it as it doesn't know what its internal values and functions are.
Remember pointers are just a number that represents the memory address of the object.
So say you myclass has a member value you want to be able to edit from python.
You need to define a set and get function
the set function should take a python value and then set the ((MyClass *)obj)->value to this value while the get function will return ((MyClass *)obj)->value
You could also construct a MyClass in python that has the appropriate design, and simply calls the C-style functions.
P.S.
I believe it's also possible to define a python class type from C++, similar to how you define functions, however I've never tried this myself.
I hope this helps you.
精彩评论