在 Mac OS X 上使用 Swig 将 C++ 封装到 Python

wrapping C++ to Python with Swig on Mac OS X

我正在尝试通过 swig 为 python 包装简单的 C++ 代码。我的密码是
hello.cpp

#include <iostream>
/*simple function for trying swig*/
char const* greet(){
    return "hello world!";
}

包装代码helloworld.i

/*interface file for swig : corresponds to hello.cpp*/
%module helloworld
%{
/*headers and declarations here*/
extern char const* greet();
%}
extern char const* greet();

我使用的命令:

swig -c++ -python helloworld.i
g++ -O2 -fPIC -c hello.cpp
g++ -O2 -fPIC -c helloworld_wrap.cxx -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7
g++ -lpython -dynamclib hello.o helloworld_wrap.o -o _helloworld.so

前三个命令运行良好,生成了所有需要的文件,但最后一个命令出现以下错误。

错误信息:

clang: warning: argument unused during compilation: '-dynamclib'
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see     invocation)

这里出了什么问题?我对此很困惑。

使用 -dynamiclib 而不是 -dynamclib

编辑(在下面回答您的评论):

我可以重现错误

Fatal Python error: PyThreadState_Get: no current thread
Abort trap: 6

如果我尝试从不同于 link 反对的 python 导入模块。

您 link 反对系统 python,因此您应该使用它。尝试:

/usr/bin/python
>>> import helloworld
>>> helloworld.greet()

可能您在某处安装了另一个 python 版本。执行 which python 查看正在调用的版本。

现在,为了 link 与正确的 python 相对应,您可以使用 python-config 来确定正确的编译器参数,或者编写一个小的 setup.py 文件并让distutils 处理编译(可能是最好的方式)。