1

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.

2
  • 1
    Your capsule points to a local variable that only exists for the duration of genFunc. I'm surprised you get an error message rather than a crash though. You need to allocate var with malloc or make it a global variable or something similar to ensure that it lives as long as the capsule. Commented Aug 10, 2016 at 14:35
  • Apologies -- this was just written as demonstration code; the real example has some malloc calls, which is probably why it produces the error. Commented Aug 11, 2016 at 8:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Apologies for late response -- but this was exactly the issue. Changing the function signature to METH_O fixed the pycapsule errors. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.