Linking C module with Python 3.7. CMake in Windows

2019-08-21 08:58发布

问题:

I'm trying to create a C library that can be called from Python, so far I've created the proxy C file that exposes the module information and the method table (For simplicity just one method is added get_cycle_count and its implementation irrelevant):

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);
}

Now, the documentation says that (Obviously) my C library has to be processed somehow so that Python can actually import it. I've gotten as far as creating a C library instead of an executable with CMake (And CLion, not VS so the compiler is gcc from MinGW) but I can't find nor understand how I'm suposed to do that with CMake.

This piece of CMake produces a file called libNESulator.a but no dll or lib files are produced and the .py file (in the same location as the .a library) can't find it when doing import libNESulator or import NESulator the latter one being the name defined in the PyModuleDef structure. So I'm pretty sure there's something missing there

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})

So.... yeah, do you have any idea how to turn that libNESulator.a into a Python callable module? What do I need to do in this CMake to make it happen?

If you have an easier way of doing it or any other way at all please feel free to propose it. I'm quite new to CMake and Python so I don't know if you need more information from me like the project structure or so but please let me know if you do.

Thanks a lot