繁体   English   中英

在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

如果我尝试从不同于链接的python导入模块。

您正在针对系统python进行链接,因此您应该使用它。 尝试:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM