在Mac OS X上使用Swig将C++包装成Python

1 投票
1 回答
1591 浏览
提问于 2025-05-10 15:12

我正在尝试用swig把简单的C++代码包装成Python可以用的。我的代码是
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)

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

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

0

使用 -dynamiclib 而不是 -dynamclib

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

我可以重现这个错误

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

如果我尝试从一个与链接的python不同的版本导入模块,就会出现这个问题。

你现在链接的是系统自带的python,所以你应该使用这个。试试:

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

可能你在其他地方安装了另一个版本的python。可以用 which python 命令查看当前调用的是哪个版本。

现在,为了链接到正确的python,你可以使用 python-config 来确定正确的编译参数,或者写一个小的 setup.py 文件,让distutils来处理编译(这可能是最好的方法)。

撰写回答