0

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

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

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

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

#include <python.h>

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

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

和 Python 脚本(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。

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

4

1 回答 1

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/以及官方文档

于 2017-08-14T18:42:18.997 回答