Skip to main content
 首页 » 编程设计

python之让我的 python c++ 扩展在 Windows 上使用 Swig 和 Distutils 进行编译

2025年05月04日8leader

我正在尝试在 Windows 上创建一个 Python C++ 扩展。我的问题是,即使在使用 swig 和 distutils 之后,我似乎也无法生成 .pyd 文件(链接错误)。下面是我一步一步做的:

在 Microsoft Visual Studio 2010 中我创建了一个类 你好.cpp:

#include "StdAfx.h" 
#include "Hello.h" 
#include <iostream> 
using namespace std; 
 
 
Hello::Hello(void) 
{ 
} 
 
void Hello::greeting(void){ 
   cout<<"Hello World!!"<<endl; 
 
} 
 
 
 
Hello::~Hello(void) 
{ 
} 

你好.h:

      #pragma once 
      class Hello 
      { 
         public: 
            Hello(void); 
            ~Hello(void); 
            void greeting(void); 
      };   

然后我创建了一个.i文件HelloWorld.i

%module HelloWorld 
 
%{ 
#include "Hello.h" 
%} 
 
%include "Hello.h" 

然后我喝了一口

swig -c++ -python -o Hello_wrap.cpp HelloWorld.i 

这似乎工作成功,生成了我预期的文件。接下来我创建了 setup.py。

from distutils.core import setup, Extension 
 
module1=Extension('HelloWorld', sources=['Hello.cpp']) 
 
setup(name='Hello_Package', version='1.0', description='This is a demo', \ 
      ext_modules=[module1]) 

写完之后,切换到所有文件存放在一起的目录后,我进入了命令行

python setup.py build 

不幸的是,这是我得到的错误

running build 
running build_ext 
building 'HelloWorld' extension 
creating build 
creating build\temp.win32-2.7 
creating build\temp.win32-2.7\Release 
c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W 
3 /GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /TpHello.cpp /Fobuild\tem 
p.win32-2.7\Release\Hello.obj 
Hello.cpp 
c:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C 
4530: C++ exception handler used, but unwind semantics are not enabled. Specify 
/EHsc 
creating build\lib.win32-2.7 
c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\link.exe /DLL /nologo /INCRE 
MENTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:initHel 
loWorld build\temp.win32-2.7\Release\Hello.obj /OUT:build\lib.win32-2.7\HelloWor 
ld.pyd /IMPLIB:build\temp.win32-2.7\Release\HelloWorld.lib /MANIFESTFILE:build\t 
emp.win32-2.7\Release\HelloWorld.pyd.manifest 
LINK : error LNK2001: unresolved external symbol initHelloWorld 
build\temp.win32-2.7\Release\HelloWorld.lib : fatal error LNK1120: 1 unresolved 
externals 
error: command '"c:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\link.exe"' 
failed with exit status 1120 

对于此链接错误,我该怎么办?我假设 swig 和 distutils 工作正常,所以我不必更改代码。请帮助!谢谢

请您参考如下方法:

尝试以下操作

module1=Extension('_HelloWorld', sources=['Hello.cpp'])