1
votes

I've wrapped a C++ class using Py++ and everything is working great in Python. I can instantiate the c++ class, call methods, etc.

I'm now trying to embed some Python into a C++ application. This is also working fine for the most-part. I can call functions on a Python module, get return values, etc.

The python code I'm calling returns one of the classes that I wrapped:

import _myextension as myext
def run_script(arg):
    my_cpp_class = myext.MyClass()
    return my_cpp_class

I'm calling this function from C++ like this:

// ... excluding error checking, ref counting, etc. for brevity ...
PyObject *pModule, *pFunc, *pArgs, *pReturnValue;

Py_Initialize();
pModule = PyImport_Import(PyString_FromString("cpp_interface"));
pFunc = PyObject_GetAttrString(pModule, "run_script");
pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, PyString_FromString("an arg"));


pReturnValue = PyObject_CallObject(pFunc, pArgs);

bp::extract< MyClass& > extractor(pReturnValue); // PROBLEM IS HERE
if (extractor.check()) {                         // This check is always false
    MyClass& cls = extractor();
}

The problem is the extractor never actually extracts/converts the PyObject* to MyClass (i.e. extractor.check() is always false).

According to the docs this is the correct way to extract a wrapped C++ class.

I've tried returning basic data types (ints/floats/dicts) from the Python function and all of them are extracted properly.

Is there something I'm missing? Is there another way to get the data and cast to MyClass?

1

1 Answers

1
votes

I found the error. I wasn't linking my bindings in my main executable because the bindings were compiled in a separate project that created the python extension only.

I assumed that by loading the extension using pModule = PyImport_Import(PyString_FromString("cpp_interface")); the bindings would be loaded as well, but this is not the case.

To fix the problem, I simply added the files that contain my boost::python bindings (for me, just wrapper.cpp) to my main project and re-built.