Pass pointer from C++ class to Boost Python script ?!!!

David Rostowsky david_rostowsky at yahoo.com
Sun Mar 28 12:48:45 EST 2004


Im a newbie to Boost and Python and need some help.

I have a C++ class:

class TestC
{
protected:
    int x;

public:
    TestC() { x = 0; };
    void Set(int val) { x = val; };
    int Get(void) { return x; };
};

In my C++ code I want to allocate an instance of TestC:
TestC * my_ptr = new TestC();

Now, I want to run a Boost Python script from inside my C++ code and
pass the address of my_ptr to the script such that the script can call
any of my classes public member functions like this:

# my python script. I know the syntax is probably not right, thats why
I need help! This is test_script.py referenced in c++ code below.
def my_script(addr_of_my_ptr):
    addr_of_my_ptr.Set(9)
    x = addr_of_my_ptr.Get()
    print x
    return 0;

So, in my C++ code, Ive been trying to do stuff like below, but with
no luck... I know I need some wacky Boost syntax to expose the class
to the Python script (I definitely need help there too). Everything
works right up until PyObject_CallObject where it crashes and burns. I
cant decode the Boost documentation properly to find the right amount
of cryptic code to use to make this work right. HELP!!!

int main()
{
    Py_Initialize();
	
    // load the module
    PyObject * module = PyImport_ImportModule("test_script");

    // dictionary of module
    PyObject * dict = PyModule_GetDict(module);

    // get a pointer to the function in the script
    PyObject * func = PyDict_GetItemString(dict, "my_script");

    // call the function
    TestC * my_ptr = new TestC();
    PyObject * pyobj = Py_BuildValue("O", my_ptr);

    // make a tuple of arguments (the numbers 2 and 3)
    PyObject *arguments = PyTuple_New(1);
    PyTuple_SetItem(arguments, 0, Py_BuildValue("O", my_ptr));

    PyObject * result = PyObject_CallObject(func, arguments);

    // show the result
    printf("Result of call: %ld\n", PyInt_AsLong(result));

    // clean up
    Py_DECREF(result);
    Py_DECREF(module);

    Py_Finalize();

    return 0;
}



More information about the Python-list mailing list