duffsterlp
duffsterlp

Reputation: 377

CPython API jiving with C++ class

I'm trying to use structs defined in the C/Python API in a C++ class. Specifically, I'm trying to define an array of structures for PyMethodDef and PyMemberDef (documentation is here):

For PyMethodDef, I am able to define a static array in a class header and declare it in the implementation file. However, doing the same thing for PyMemberDef gives me the following errors:

error: elements of array 'PyMemberDef members_ []' have incomplete type
error: storage size of 'members_' isn't known.

I think I can see why PyMethodDef works but PyMemberDef does not. In the Python source, PyMethodDef is defined as such:

struct PyMethodDef {
    ...
    ...
};

typedef struct PyMethodDef PyMethodDef;

whereas PyMemberDef is defined as such:

typedef struct PyMemberDef {
   ...
   ...
} PyMemberDef;

I confirmed this to be the cause of the problem by defining PyMemberDef the way PyMethodDef is in my code and confirming that it compiles without error. However, I don't know how to rectify this. I would prefer not to hardcode and redefine it myself. Hope this is clear enough. I can provide more detail upon request. Thanks.

Upvotes: 5

Views: 1261

Answers (1)

Michał Górny
Michał Górny

Reputation: 19273

If you tried with clang, it would give you a bit more meaningful error message like:

pymountboot.cxx:45:20: error: variable has incomplete type 'PyMemberDef'
static PyMemberDef foo_members[] = {
                   ^
/usr/include/python2.7/object.h:381:12: note: forward declaration of 'PyMemberDef'
    struct PyMemberDef *tp_members;
           ^
1 error generated.

So, it seems that PyMemberDef is not actually declared here.

A quick grep shows that it is declared in structmember.h, and that file is not included in Python.h.

Then a quick look at the Python docs on Defining new types and you could notice that the example starts with:

#include <Python.h>
#include "structmember.h"

Upvotes: 10

Related Questions