Ben Campbell
Ben Campbell

Reputation: 4678

How do I pass a instance member function as a PyCFunction type using the Python C/C++ Interface

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?

Upvotes: 0

Views: 461

Answers (1)

Zorg
Zorg

Reputation: 1018

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.

Upvotes: 1

Related Questions