【问题标题】:Trying to Call Python from C尝试从 C 调用 Python
【发布时间】:2012-09-09 21:08:01
【问题描述】:
#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

我已经坚持了很长一段时间,如果有任何建议,我将不胜感激。

【问题讨论】:

    标签: python c visual-c++


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2011-07-02
        • 2010-10-13
        • 2021-09-08
        • 2014-10-19
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多