无法导入用C

时间:2017-08-14 17:40:59

标签: python c python-c-api pyd

我一直在尝试研究如何从C脚本创建.pyd(Python扩展模块)文件(没有swig或除MinGW之外的任何其他内容)并且已成功将其构建为.pyd

但是当我尝试导入模块时会出现问题。

如果我运行它,模块会成功运行(据我所见),然后会出现一条错误Python Has Stopped Working并且它会在不执行其余程序的情况下关闭。

这是我的C脚本(test.c):

#include <python.h>

int main()
{
    PyInit_test();
    return 0;
}

int PyInit_test()
{
    printf("hello world");
}

Python Script(file.py):

import test
print('Run From Python Extension')

我用以下代码编译了脚本:

gcc -c file.py
gcc -shared -o test.pyd test.c

在命令提示符下编译并使用python 3.6(在Windows 10上运行)时,我找不到任何错误。

我在这个问题上找不到多少,并且宁愿远离Cython(我已经知道C)和Swig。

任何帮助告诉我出了什么问题都会很棒。

1 个答案:

答案 0 :(得分:4)

创建Python扩展与编写常规C代码完全不同。你所做的只是创建一个有效的C程序,但这对Python没有意义。

你的程序应该是什么样的(它只是一个骨架,而不是正确的工作代码):

#include <Python.h>
#include <stdlib.h>

static PyObject* test(PyObject* self, PyObject* args)
{
    printf("hello world");
    return NULL;
}

static PyMethodDef test_methods[] = {
    {"test", test, METH_VARARGS, "My test method."},
    {NULL, NULL, 0, NULL} /* Sentinel */
};

PyMODINIT_FUNC init_test_methods() {
    Py_InitModule("test", test_methods);
}

int main(int argc, char** argv)
{
    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(argv[0]);

    /* Initialize the Python interpreter. Required. */
    Py_Initialize();

    /* Add a static module */
    init_test_methods();
}

我建议您通过以下链接了解详情:http://dan.iel.fm/posts/python-c-extensions/以及official docs