0
点赞
收藏
分享

微信扫一扫

[WIN10 Python] 记Python C扩展中出现LINK : error LNK2001: 无法解析的外部符号 PyInit_xxx 的问题

吃面多放酱 2022-04-30 阅读 88

小白学python

为了提高python 的运行速度,我想使用C 扩展,在网上查了一些资料后,我先按这个大佬的程序跑了一遍,发现可以跑通。

但是当我自己写程序之后,在setup 的时候经常出现LINK : error LNK2001: 无法解析的外部符号 PyInit_xxx 的问题,后来我一个个试,发现了问题。

首先,setup.py 的程序:

from distutils.core import setup, Extension

module1 = Extension('demo', // extension 的name
                    sources = ['demo.c']
                    )

setup (name = 'a demo extension module',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

demo.c 的程序:

// pulls in the Python API 
#include <Python.h>
static int mul(int a,int b){
    return a*b;
}
static int add(int a,int b){
    return a+b;
}
// C function always has two arguments, conventionally named self and args
// The args argument will be a pointer to a Python tuple object containing the arguments.
// Each item of the tuple corresponds to an argument in the call's argument list.
static PyObject* demo_mul_and_add(PyObject *self, PyObject *args)
{
    const int a, b;
    // convert PyObject to C values
    if (!PyArg_ParseTuple(args, "ii", &a, &b))
        return NULL;
    int c=mul(a,b);
    int d=add(c,c);
    // convert C value to PyObject
    return Py_BuildValue("i", d);
}

// module's method table
static   PyMethodDef DemoMethods[] = {
    {"mul_and_add", demo_mul_and_add, METH_VARARGS, "Mul and Add two integers"},
    {NULL, NULL, 0, NULL} 
};
static struct PyModuleDef demomodule = {
    PyModuleDef_HEAD_INIT,
    "demo", /* module name */
    NULL, /* module documentation, may be NULL */
    -1,
    DemoMethods /* the methods array */
};

PyMODINIT_FUNC PyInit_demo(void)
{
    return PyModule_Create(&demomodule);
}

问题就出在这个Extension 的name 和C 程序中的PyInit_demo上。

PyInit_xxx 是初始化函数,这个xxx 的命名要和这个Extension 的name要一样,不然就会出现LINK : error LNK2001: 无法解析的外部符号 PyInit_xxx 的错误。

举报

相关推荐

0 条评论