编译后通过Python调用C函数

2024-09-27 07:35:42 发布

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

在尝试从Python调用c函数时(在前一篇文章Calling a C function from a Python file. Getting error when using Setup.py file),我已经将代码编译成一个.pyd文件,并正在测试程序。 然而,我遇到了错误

AttributeError: 'module' object has no attribute 'addTwo'

我的测试文件如下:

import callingPy
a = 3
b = 4
s = callingPy.addTwo(a, b)
print("S", s)

其中callingPy是通过编译生成的以下.c文件(转换为.pyd):

#include <Python.h>
#include "adder.h"

static PyObject* adder(PyObject *self, PyObject *args)       
{
    int a;
    int b;
    int s;
    if (!PyArg_ParseTuple(args,"ii",&a,&b))                      
       return NULL;
    s = addTwo(a,b);                                                
    return Py_BuildValue("i",s);                                
}

/* DECLARATION OF METHODS*/
static PyMethodDef ModMethods[] = {
    {"modsum", adder, METH_VARARGS, "Descirption"},         
    {NULL,NULL,0,NULL}
};

// Module Definition Structure
static struct PyModuleDef summodule = {
   PyModuleDef_HEAD_INIT,"modsum", NULL, -1, ModMethods     
};

/* INITIALIZATION FUNCTION*/
PyMODINIT_FUNC PyInit_callingPy(void)
{
    PyObject *m;
    m = PyModule_Create(&summodule);
    return m; 
}

任何帮助都将不胜感激! 非常感谢。你知道吗


Tags: 文件returnincludeargsstaticnullfileint
1条回答
网友
1楼 · 发布于 2024-09-27 07:35:42

扩展模块中唯一的函数以modsum的名称导出到Python。你打电话给addTwo。这似乎不言自明。你知道吗

看起来在C层,有一个名为addTwo的原始C函数为C函数adder工作,然后以modsum的名称导出到Python。因此,您应该重命名导出,或者使用正确的名称调用它:

s = callingPy.modsum(a, b)

看起来你复制粘贴了一个骨架扩展模块,切换了一个很小的内部模块,并且没有修复任何导出或名称。你知道吗

相关问题 更多 >

    热门问题