简单的Python C ++扩展无法在Windows上编译

时间:2018-02-22 18:35:25

标签: python windows

我正在尝试研究如何使用C ++进行Python扩展;我有一个简单的“hello world”级别测试程序,它将使用distutils进行编译并在Linux(Ubuntu)上正常运行,但在Windows上失败。我在Windows 7上使用64位Python 2.7。

测试用例是三个文件:

setup.py 
foobar/__init__.py
foobar/testext.cpp

setup.py

from distutils.core import setup, Extension
setup(name = "foobar",
      packages = ['foobar'],
      ext_modules = [Extension('foobar/test',
                               sources = ['foobar/testext.cpp'])])

foobar/__init__.py :(我想这是不必要的?)

import test
def foobar():
    return test.testfunc() * 10

foobar/testext.cpp

# include <Python.h>

static PyObject * test_func(PyObject *self, PyObject *args)
{
  return Py_BuildValue("i", 6);
};

static PyMethodDef TestMethods[] = {
  {"testfunc", test_func, METH_VARARGS, "Blah."},
  {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC inittest(void)
{
  (void) Py_InitModule("test", TestMethods);
}

这会编译“setup.py build”而不会抱怨。但是,如果我进入lib目录并尝试导入包,则会出错:

Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import foobar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "foobar\__init__.py", line 1, in <module>
    import test
ImportError: DLL load failed: %1 is not a valid Win32 application.

我知道此错误消息通常表示尝试使用64位的Python副本加载32位二进制文​​件,但奇怪的是,如果我尝试导入,则会收到相同的消息带有32位Python副本的模块。同时,相同文件的相同程序适用于Ubuntu。有什么想法吗?

更正:我傻了;当我实际删除预先存在的“build”目录并重新编译时,它确实会出错。我想更新我的setuptools副本已经解决了这个问题,但是发生的事情是终端命令“del build”只是悄悄地没有做任何事情(argh,Windows!)。

正在运行setup.py build显示:

C:\Users\Max\Downloads\worksonlinux\pyextstuff>setup.py build
running build
running build_py
creating build
creating build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\foobar
copying foobar\__init__.py -> build\lib.win-amd64-2.7\foobar
running build_ext
building 'foobar/test' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
creating build\temp.win-amd64-2.7\Release\foobar
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I
C:\Python27\include -IC:\Python27\PC /Tpfoobar/testext.cpp /Fobuild\temp.win-amd64-2.7\Release\foobar/testext.
obj
testext.cpp
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH
:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild\amd64 /EXPORT:initfoobar/test build\temp.win-amd64-2.7\Release\
foobar/testext.obj /OUT:build\lib.win-amd64-2.7\foobar\test.pyd /IMPLIB:build\temp.win-amd64-2.7\Release\fooba
r\test.lib /MANIFESTFILE:build\temp.win-amd64-2.7\Release\foobar\test.pyd.manifest
LINK : error LNK2001: unresolved external symbol initfoobar/test
build\temp.win-amd64-2.7\Release\foobar\test.lib : fatal error LNK1120: 1 unresolved externals
error: command '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\link.exe"' failed with exit s
tatus 1120

0 个答案:

没有答案