#include <Python.h>
static PyObject* helloworld(PyObject* self)
{
return Py_BuildValue("s", "Hello, Python extensions!!");
}
static char helloworld_docs[] =
"helloworld( ): Any message you want to put here!!\n";
static PyMethodDef helloworld_funcs[] = {
{"helloworld", (PyCFunction)helloworld,
METH_NOARGS, helloworld_docs},
{NULL}
};
void inithelloworld(void)
{
Py_InitModule3("helloworld", helloworld_funcs,
"Extension module example!");
}
我一直试图用C语言扩展Python,因此一直试图在Visual Studio中编译上面的代码。但是,我反复得到以下错误:
LINK : fatal error LNK1104: cannot open file 'python27.lib'
将python27.lib添加到项目后,我将得到以下错误:
HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_BuildValue
HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_InitModule4
我在这件事上耽搁了很长一段时间,如果有什么建议,我将不胜感激。
最佳答案
假设您的代码是正确的,最好的方法是使用setup.py
文件。例如,下面是我创建hello world模块时使用的代码:
设置.py:
from distutils.core import setup, Extension
setup(
ext_modules = [
Extension("ext1", sources=["ext1.c"]),
],
)
在这里,“
ext1"
将替换模块名,而“ext1.c”将替换c源文件名。然后在终端上运行,比如:
setup.py install
为了进一步参考,这里是我的C源:
扩展1.c:
#include "Python.h"
static PyObject *
hello_world(PyObject * self, PyObject * args)
{
return Py_BuildValue("s", "Hello World!");
}
static PyMethodDef
module_functions[] = {
{ "hello_world", hello_world, METH_VARARGS, "Says Hello World."},
{ NULL }
};
void
initext1(void)
{
Py_InitModule3("ext1", module_functions, "My additional Module");
}