3

I'm following the official tutorial of Python API to create a simple extension type in C++ for Python. But I can't get my code successfully compiled. Because when I use T_INT in my code I got an error said 'T_INT' was not declared in this scope. Have I forgot anything? I can't find an answer on the tutorial.

Here is my C++ code:

#define PY_SSIZE_T_CLEAN
#include <python3.6/Python.h>
#include <stddef.h>

typedef struct {
    PyObject_HEAD
    int num;
} MyObject;

static PyMemberDef MyMembers[] = { 
    { "num", T_INT, offsetof(MyObject, num), 0, NULL },
    { NULL }
};

static PyTypeObject MyType = []{ 
    PyTypeObject ret = { 
        PyVarObject_HEAD_INIT(NULL, 0)
    };  
    ret.tp_name = "cpp.My";
    ret.tp_doc = NULL;
    ret.tp_basicsize = sizeof(MyObject);
    ret.tp_itemsize = 0;
    ret.tp_flags = Py_TPFLAGS_DEFAULT;
    ret.tp_new = PyType_GenericNew;
    ret.tp_members = MyMembers;
    return ret;
}();

static PyModuleDef moddef = []{ 
    PyModuleDef ret = { 
        PyModuleDef_HEAD_INIT
    };  
    ret.m_name = "cpp";
    ret.m_doc = NULL;
    ret.m_size = -1; 
    return ret;
}();

PyMODINIT_FUNC
PyInit_cpp(void)
{
    PyObject *mod;
    if (PyType_Ready(&MyType) < 0)
        return NULL;
    mod = PyModule_Create(&moddef);
    if (mod == NULL)
        return NULL;
    Py_INCREF(&MyType);
    PyModule_AddObject(mod, "My", (PyObject *)&MyType);
    return mod;
}

I compile with the following command:

g++ -std=c++11 -shared -fPIC -o cpp.so tt.cpp

And the first error I got is:

tt.cpp:10:11: error: 'T_INT' was not declared in this scope

My g++ version is 7.3.0

Cosmo
  • 836
  • 1
  • 12
  • 27

2 Answers2

6

Yes, you've forgotten something, specifically the second of the two includes in the tutorial:

#include "structmember.h"

That's the one that provides T_INT. (You might have it in python3.6/structmember.h, looking at your existing imports.)

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks. That solved my problem. I have tried `#include "structmember.h"` but it was not found. But my problem I forgot to `#include "python3.6/structmember.h"`. – Cosmo Apr 25 '19 at 09:45
1

I think you have forgotten to add another include statement in your code.

Can you try with including

#include "structmember.h"

in your code(maybe you need to search for the header) as you included #include <python3.6/Python.h> in your code it is possible that you have to do #include python3.6/structmember.h and also there is another answer to the somewhat same question here.

ShivamPR21
  • 119
  • 1
  • 8