开发者

PY_MAJOR_VERSION undefined when compiling Python C module for Python 3.x

开发者 https://www.devze.com 2023-01-28 02:55 出处:网络
I am trying to upgrade a small C module to work with Python 3.x and having trouble getting it to compile. My roadblock right now is that the preprocessor defines I am supposed to be using to check the

I am trying to upgrade a small C module to work with Python 3.x and having trouble getting it to compile. My roadblock right now is that the preprocessor defines I am supposed to be using to check the Python version aren't working.

The module contains two .c files at the moment (I've temporarily commented out the rest). In both files, PY_MAJOR_VERSION is undefined so the compiler cannot use the Python 3.x specific definitions where needed.

mymodule.c:

#ifndef PY_MAJOR_VERSION
#error Major version not defined!
#endif

#if PY_MAJOR_VERSION >= 3
#define PY3K
#endif

#include "Python.h"
#include "myobj.h"

/* omitted: irrelevant boilerplate structs */

PyMODINIT_FUNC
initmymodule(void)
{
    PyObject* m;

#ifdef PY3K
    m = PyModule_Create(&mymodule_struct);
#else
    (void) Py_InitModule("mymodule", MyModMethods);
    m = Py_InitModule3("mymodule", NULL,
               "My Module");
#endif

    /* omitted: the rest of the module init code */
}

myobj.c:

#ifndef PY_MAJOR_VERSION
#error Major version not defined!
#endif

#if PY_MAJOR_VERSION >= 3
#define PY3K
#endif

#include "Python.h"
#define NEED_STATIC
#include "myobj.h"
#undef NEED_STATIC

#ifdef PY3K
#define PYSTR_FROMC PyUnicode_FromString
#define PYSTR_FORMAT PyUnicode_Format
#define PYINT_FROMC PyLong_FromLong
#else
#define PYSTR_FROMC PyString_FromString
#define PYSTR_FORMAT PyString_Format
#define PYINT_FROMC PyInt_FromLong
#endif

/* omitted: rest of module code */

setup.p开发者_StackOverflow中文版y:

from distutils.core import setup, Extension

module1 = Extension('mymodule', sources = ['mymodule.c', 'myobj.c'])
setup(name='mymodule', version='0.1', ext_modules=[module1])

I am building with c:\python31\python setup.py bdist_wininst

Where is PY_MAJOR_VERSION supposed to get defined? Is it something I need to tell distutils to pass to the compiler?


I figured out what I was doing wrong. It's Python.h that defines PY_MAJOR_VERSION. By putting my #defines ahead of my #includes, I missed out on the definition. I don't know why I was thinking that the build system would define it for me...

Moving the #if PY_MAJOR_VERSION >= 3 so that it executes after #include "Python.h" fixes the problem. I will leave this here in case someone else is as dumb as I was, because there was nothing useful on Google for this query.

0

精彩评论

暂无评论...
验证码 换一张
取 消