I am trying to embed python within an exiting C++ application. However I am stuck at trying to call an instance member function from the python script.
I have an existing class in which I have a private member function that wraps the native function and meets the PyCFunction interface.
class MY_CLASS {
public:
void MY_CLASS();
void submit(TypeA a, int b);
private:
PyObject* PythonMethod_submit(PyObject*, PyObject*);
}
When I create the PyMethodDef I use the method name to identify the function I want however I get a compliation error indicating I have to the wrong type signature.
MY_CLASS::MY_CLASS() {
// Python C/API Intilization stuff
PyMethodDef ModuleMethods[] = {
{ "submit",
PythonMethod_submit,
METH_VARARGS,
"docstring" }
};
Py_InitModule("myclass", ModuleMethods);
// Further interaction with the embeded interpreter
}
If I use a static function as described in the Python C API this process works, when I use the class member I recieve an error asserting PyObject* (MY_CLASS::)(PyObject*, PyObject*) does not match PyObject* (*)(PyObject*, PyObject*)
.
Is it possible to pass a member function as function pointer as stated in the error?
No. A non-static member function has a MY_CLASS *
implicitly passed in (as this
), whereas a static member function, which behaves like a C function, does not. See this page for the different type signatures: http://www.parashift.com/c++-faq/fnptr-vs-memfnptr-types.html
What you can do as an alternative is have a member in your Python object that holds a pointer ( MY_CLASS *
) to your C++ object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.