用python3.7链接C模块。在Windows中制作

2024-10-02 20:33:27 发布

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

我正在尝试创建一个可以从Python调用的C库,到目前为止,我已经创建了一个代理C文件,它公开了模块信息和方法表(为简单起见,只添加了一个方法get_cycle_count,它的实现与此无关):

static PyMethodDef NESulator_methods[] = {
        {"NESulator",  get_cycle_count, METH_VARARGS, "Retrieves the current cycle count"},
        {NULL, NULL, 0, NULL}        /* Sentinel */
};

static struct PyModuleDef NESulator_module = {
        PyModuleDef_HEAD_INIT,
        "NESulator",    /* name of module */
        NULL,           /* module documentation, may be NULL */
        -1,             /* size of per-interpreter state of the module,
                           or -1 if the module keeps state in global variables. */
        NESulator_methods
};

/*
 * Should this be called somewhere? Will the linker do something with this?
 */
PyMODINIT_FUNC PyInit_NESulator(void)
{
    return PyModule_Create(&NESulator_module);
}

现在,documentation表示(显然)必须以某种方式处理我的C库,以便Python能够实际导入它。我已经用CMake创建了一个C库,而不是一个可执行文件(CLion,不是VS,所以编译器是MinGW的gcc),但是我找不到也不明白我是如何用CMake来完成这项工作的。你知道吗

这段CMake生成一个名为libNESulator.a的文件,但不生成dlllib文件,并且.py文件(与.a库位于同一位置)在执行import libNESulatorimport NESulator时找不到它,后者是PyModuleDef结构中定义的名称。所以我很确定那里少了些什么

project(NESulator)
set(CMAKE_C_STANDARD 11)
add_subdirectory(src)

find_package(PythonLibs REQUIRED)

include_directories(${PYTHON_INCLUDE_DIRS})

add_library(NESulator "all of my .c files in the src directory previously included" )

target_link_libraries(NESulator ${PYTHON_LIBRARIES})

所以。。。。是的,您知道如何将libNESulator.a转换为Python可调用模块吗?我需要怎么做才能让它发生?你知道吗

如果你有一个更简单的方法或任何其他方式,请随时提出它。我对CMake和Python还比较陌生,所以我不知道您是否需要我提供更多的信息,比如项目结构等,但是如果需要的话请告诉我。你知道吗

多谢了


Tags: 模块文件ofthe方法cmake信息get