Search code examples
pythonc++python-3.xpython-c-api

Python C API: T_INT was not declared in this scope


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


Solution

  • 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.)