1
我試圖建立用C Python模塊,並停留在一個問題:定製的C模塊包括
當我包括額外的頭文件(test.h
),模塊編譯沒有警告,但後來import
這個模塊,Python抱怨未定義的符號maketest
。
我的模塊結構如下(模塊被命名爲spam
):
spammodule.c
spam\
├spammodule.c
|setup.py
├─src\
|── test.c
|── test.h
:
#include <Python.h>
#include "test.h"
static PyObject * SpamError;
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
maketest(); // <---- calling function from additional file
if(!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
if (sts < 0) {
PyErr_SetString(SpamError, "System command failed");
return NULL;
}
return PyLong_FromLong(sts);
}
PyMODINIT_FUNC
initspam(void)
{
PyObject *m;
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS, "Execute a shell command."},
{NULL, NULL, 0, NULL}
};
m = Py_InitModule("spam", SpamMethods);
if (m == NULL)
return;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
}
int
main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
initspam();
}
的setupy.py
內容:中src/test.h
from setuptools import setup,Extension
spam_module = Extension('spam',
sources = ['spammodule.c'],
include_dirs=['src/'],)
setup (name = 'Spam',
version = '1.0',
description = 'Sample module.',
ext_modules = [ spam_module ])
內容:
void maketest(void);
的src/test.c
內容:
#include "test.h"
void maketest() {
printf("test passed");
}
我編譯一切與python setup.py build
,運行Python提示符我試圖導入我的模塊,並且得到錯誤後:
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import spam
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: ./spam.so: undefined symbol: maketest
是否有人有線索怎麼回事?
你絕對無法將src/test.c的目標文件鏈接到'.so'中。將'src/test.c'添加到源列表中。 –
你說得對,我認爲包括'src/*'文件已經足夠了,但是沒有,正如你所說的其他文件應該列在源元組中,謝謝。我在我的帖子後添加了答案 – user3459276
不,你應該*發佈*你的答案作爲*答案*。然後*接受它*! –