3

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 pointer:

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>())
1
  • 2
    What you're doing is perfectly fine, C++-wise. How are you passing the pointer to Python? Commented Jun 29, 2011 at 20:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.