我正在尝试使用 Cython 从 python 生成 c 代码,但名称修饰似乎存在一些问题。我首先生成将代码从 python 转换为 c 代码,然后使用 gcc 将代码编译为 .so 。我想使用 cython 而不是 C/python API 的原因是因为我稍后将在更复杂的类上使用它,我希望稍后成为一个速度库(我很难找到那些去的人)从 python 到 C++,因为通常是相反的方式)。下面是我必须尝试执行代码(但失败)的所有代码。任何意见将不胜感激。谢谢!
#hello.pyx
def say_hello():
print "Hello World!"
#generate the c code
cython -a hello.pyx
#creates the shared library
gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.6 -o libhello.so hello.c
//temp.cpp
#include <iostream>
extern "C" {
void say_hello();
};
using namespace std;
int main(){
say_hello();
return 1;
};
#attempt to compile (this is where it fails)
g++ -I/usr/include/python2.6/ -lpython2.6 -L./ -lhello temp.cpp -o temp
这是错误消息:
/tmp/ccpKHOMl.o: In function main: temp.cpp:(.text+0x5): undefined reference to say_hello' /tmp/ccpKHOMl.o:
In function __static_initialization_and_destruction_0(int, int):
temp.cpp:(.text+0x33): undefined reference to std::ios_base::Init::Init()
temp.cpp:(.text+0x38): undefined reference to std::ios_base::Init::~Init()
collect2: ld returned 1 exit status
您将无法以这种方式获得您想要的互操作。如果您打开并检查 hello.c,您将不会在其中的任何位置找到“static int say_hello”。 Cython 的设计目的是让 Python 使用 C 库,而不是让 C 库使用 python。
您可以在文档中查看此处,但不幸的是,这种支持仍然适用于“负责”的 python 解释器,而您正在寻找的是相反的方式。
http://docs.python.org/release/2.5.4/ext/callingPython.html http://docs.python.org/release/2.5.4/ext/callingPython.html
还有“在另一个应用程序中嵌入 Python”的入门读物
http://docs.python.org/2/extending/embedding.html http://docs.python.org/2/extending/embedding.html
我不知道你的要求是什么,但在某些情况下,你可以成功地将数据写入文件,调用Python程序来咀嚼它,然后解析另一个文件的结果。它比将内容保存在内存中有点丑陋和慢,但在许多情况下它是完全可行的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)