尝试从C调用Python

2024-09-26 22:10:35 发布

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

#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,因此我一直试图在visualstudio中编译上面的代码。但是,我反复得到以下错误:

^{pr2}$

在将python27.lib添加到项目中之后,我得到以下错误:

HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_BuildValue
HiWorld.obj : error LNK2001: unresolved external symbol __imp__Py_InitModule4

我在这件事上已经有一段时间了,如果有任何建议,我将不胜感激。在


Tags: pyobjdocs错误staticerrorexternalhelloworld
2条回答

这是一个链接问题,最常见的错误是忘记了发布配置文件和调试配置文件使用不同的符号集,因此只能针对不同版本的库成功链接;这意味着在调试模式下,您应该提供library-debugVersion.lib和发布library.lib。在

我也没有过多地使用visualstudio,但我认为将我经常需要的所有库放在公共文件夹中会更方便,这类似于C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\这样,无论单个项目的设置是什么,VS都可以自动为您找到合适的库。在

假设您的代码是正确的,使其工作的最佳方法是使用setup.py文件。例如,下面是我创建hello world模块时使用的代码:

在设置.py公司名称:

from distutils.core import setup, Extension

setup(
    ext_modules = [
        Extension("ext1", sources=["ext1.c"]),
   ],
)

在这里,“ext1"”将替换为您的模块名,而“''ext1.c”将替换为您的c源文件名。在

然后从这样的终端运行它:

^{pr2}$

仅供进一步参考,以下是我的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");
}

相关问题 更多 >

    热门问题