创建python modu时出错

2024-10-02 18:21:42 发布

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

我有一个C代码,它调用一个名为SetFlags的Fortran子例程。我想把这个C代码转换成python模块。它创建了一个.so文件,但是我不能将这个模块导入python。我不确定我的错误是使用distutils创建模块还是链接到fortran库。 这是我的setflagsmodule.c文件

#include <Python/Python.h>
#include "/Users/person/program/x86_64-Darwin/include/Cheader.h"
#include <stdlib.h>
#include <stdio.h>

static char module_docstring[] = 
    "This module provides an interface for Setting Flags in C";

static char setflags_docstring[] = 
    "Set the Flags for program";



static PyObject * setflags(PyObject *self, PyObject *args)
{
    int *error;
    const int mssmpart;
    const int fieldren;
    const int tanbren;
    const int higgsmix;
    const int p2approx;
    const int looplevel;
    const int runningMT;
    const int botResum;
    const int tlcplxApprox;


    if (!PyArg_ParseTuple(args, "iiiiiiiiii", &error,&mssmpart,&fieldren,&tanbren,&higgsmix,&p2approx,&looplevel,&runningMT,&botResum,&tlcplxApprox))
        return NULL;

    FSetFlags(error,mssmpart,fieldren,tanbren,higgsmix,p2approx,looplevel,runningMT,botResum,tlcplxApprox); //Call fortran subroutine
    return Py_None;
}

static PyMethodDef setflags_method[] = {
    {"FSetFlags", setflags, METH_VARARGS, setflags_docstring},
    {NULL,NULL,0,NULL}
};

PyMODINIT_FUNC init_setflags(void)
{
    PyObject *m;
    m = Py_InitModule3("setflags", setflags_method, module_docstring);
        if (m == NULL)
            return;
}

这是我的安装文件名为设置标志.py公司名称:

^{pr2}$

我使用以下方法构建模块:

python setflags.py build_ext --inplace

当我尝试导入python模块时:

>>> import setflags
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initsetflags)

有人对这个有什么要紧的建议吗?在

如有任何帮助,我们将不胜感激,并提前感谢您抽出时间。在


Tags: 模块includestaticerrornullintdocstringmodule
1条回答
网友
1楼 · 发布于 2024-10-02 18:21:42

这个问题很简单,但很容易漏掉。在

请注意您得到的错误:

ImportError: dynamic module does not define init function (initsetflags)

现在看看你的代码:

^{pr2}$

您定义了init_setflags,而不是initsetflags。只要去掉多余的下划线,它就可以工作了。在


来自The Module's Method Table and Initialization Function的文档:

The initialization function must be named initname(), where name is the name of the module…


您经常在示例中看到名为init_fooinit函数的原因是它们通常初始化一个模块_foo.so,然后由一个纯Python模块foo.py包装。在

相关问题 更多 >