gpt4 book ai didi

python - 尝试从 C 调用 Python

转载 作者:行者123 更新时间:2023-11-28 19:26:03 24 4
gpt4 key购买 nike

#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 源代码:

ext1.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");
}

关于python - 尝试从 C 调用 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342993/

24 4 0
文章推荐: Python urllib2 : How to eliminate urllib2 add it's own headers
文章推荐: python - 从逐笔报价数据到 Renko 图表
文章推荐: python - 如何从