metm
metm

Reputation: 43

Passing a C++ pointer between C and Python

I have a python extension module written in C++, which contains multiple functions. One of these generates an instance of a custom structure, which I then want to use with other functions of my module in Python as follows

import MyModule
var = MyModule.genFunc()
MyModule.readFunc(var)

To do this, I've tried using PyCapsule objects to pass a pointer to these objects between Python and C, but this produces errors when attempting to read them in the second C function ("PyCapsule_GetPointer called with invalid PyCapsule object"). Python, however, if asked to print the PyCapsule object (var) correctly identifies it as a "'capsule object "testcapsule"'. My C code appears as follows:

struct MyStruct {
    int value;
};

static PyObject* genFunc(PyObject* self, PyObject *args) {
    MyStruct var;
    PyObject *capsuleTest;

    var.value = 1;
    capsuleTest = PyCapsule_New(&var, "testcapsule", NULL);
    return capsuleTest;
}

static PyObject* readFunc(PyObject* self, PyObject *args) {
    PyCapsule_GetPointer(args, "testcapsule");
    return 0;
}

Thank you for your help.

Upvotes: 1

Views: 1603

Answers (1)

tynn
tynn

Reputation: 39853

Like stated in a comment to your question, you'll run into an issue when reading data from the local variable MyStruct var. For this you can use the third destructor to PyCapsule_New.

But that's not the reason for your problem just now. You're using PyCapsule_GetPointer(args, "testcapsule") on the args parameter. And since it's not a capsule, even though var is one, you might have defined the signature of the function as METH_VARARGS. Instead you need to unpack the tuple or use METH_O.

Upvotes: 1

Related Questions