cec*_*rik 0 c python visual-studio-2008 python-3.x
我正在尝试升级一个小型C模块以使其与Python 3.x兼容,并且无法使其编译。我现在的障碍是预处理器定义了我应该用来检查Python版本是否正常的代码。
目前,该模块包含两个.c文件(我暂时将其余文件注释掉了)。在这两个文件中,PY_MAJOR_VERSION均未定义,因此编译器无法在需要的地方使用特定于Python 3.x的定义。
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 */
}
Run Code Online (Sandbox Code Playgroud)
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 */
Run Code Online (Sandbox Code Playgroud)
setup.py:
from distutils.core import setup, Extension
module1 = Extension('mymodule', sources = ['mymodule.c', 'myobj.c'])
setup(name='mymodule', version='0.1', ext_modules=[module1])
Run Code Online (Sandbox Code Playgroud)
我正在与 c:\python31\python setup.py bdist_wininst
PY_MAJOR_VERSION应该在哪里定义?我需要告诉distutils传递给编译器吗?
我发现自己在做什么错。定义PY_MAJOR_VERSION的是Python.h。通过将#defines放在#includes之前,我错过了定义。我不知道为什么我会认为构建系统会为我定义它...
移动#if PY_MAJOR_VERSION> = 3,使其在#include“ Python.h”之后执行即可解决该问题。如果其他人像我一样愚蠢,我将在此保留此内容,因为Google对此查询没有任何帮助。