未定义对“PyString”FromString的引用

2024-04-29 01:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有C码:

... [SNIP] ...
for(Node = Plugin.Head; Node != NULL; Node = Node->Next) {
    //Create new python sub-interpreter
    Node->Interpreter = Py_NewInterpreter();
    if(Node->Interpreter == NULL) {
        Die("Py_NewInterpreter() failed");
    }

    //Create path to plugins main source file
    snprintf(Filename, FILENAME_MAX, "%s/main.py", Node->File);

    //Convert filename to python string
    PFilename = PyString_FromString(Filename);
    if(PFilename == NULL) {
        Die("PyString_FromString(%s) failed", Filename);
    }

    //Import plugin main source file
    PModule = PyImport_Import(PFilename);
    if(PModule == NULL) {
        Die("PyImport_Import(%s) failed", Filename);
    }

    //Deallocate filename
    Py_DECREF(PFilename);

    //Get reference to onLoad function from module
    PFunction = PyObject_GetAttrString(PModule, "onLoad");
    if(PFunction == NULL) {
        Die("PyObject_GetAttrString() failed");
    }
}
... [SNIP] ...

编译时出现此错误:

/tmp/ccXNmyPy.o: In function `LoadPlugins':
/home/alex/Code/Scribe/Scribe.c:693: undefined reference to `PyString_FromString'
collect2: error: ld returned 1 exit status

Python.h包含在源文件的顶部。

我正在编译:

gcc -funwind-tables -rdynamic -I /usr/include/python2.7/ -g -o Scribe Scribe.c -lcurses `python-config --cflags` `python-config --ldflags` -Wall

我将代码基于Python C-Api文档,从这里开始:

http://docs.python.org/2/c-api/

具体来说:

http://docs.python.org/2/c-api/string.html?highlight=pystring_fromstring#PyString_FromString

我不知道为什么会这样,哈尔普?=丙


Tags: topyimportnodeifmainfilenamenull
2条回答

图书馆的秩序很重要。尝试使用库列表中最后一个出现的-lpython2.7进行编译。

在马蒂诺的帮助下解决了这个问题。

找出python-config --cflagspython-config --ldflags行生成的标志,这些标志在搜索路径中包含python3.3 include目录并链接了python3.3库。

当然python3.3不能很好地与python2.7c-API一起工作,这就是导致这个问题的原因。

我的解决方案是复制python-config --cflagspython-config --ldflags的输出并对其进行编辑,使其包含python2.7而不是python3.3m:

-I/usr/include/python2.7 -I/usr/include/python2.7 -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2

-lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic

而不是:

-I/usr/include/python3.3m -I/usr/include/python3.3m -Wno-unused-result -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4 -D_FORTIFY_SOURCE=2

-lpthread -ldl -lutil -lm -lpython3.3m -Xlinker -export-dynamic

相关问题 更多 >