'How do I properly link python extension modules in C++?

I have a simple example python extenstion I want to use from C/C++. The code is as follows

example.pxy:

from numpy import random
cdef public void somefunc():
    print(random.randint(500))

setup.py:

from setuptools import setup
cfom Cython.Build import cythonize
import numpy


setup(
    ext_modules=cythonize("example.pyx"),
    zip_safe=False,
    include_dirs=[numpy.get_include()]
)

Running python3 setup.py build_ext --inplace --compiler="mingw32" -DMS_WIN64 then creates example.c, example.h and example.cp310-win_amd64.pyd. The C++ code I am using to call someFunc is:

example.cpp:

#include <Python.h>    
#include "example.h" 

int main()
{
    Py_Initialize();

    somefunc();

    return 0;
}

This I compile using g++ example.cpp -DMS_WIN64. But that command seems to be incomplete. There are sill objects left that need to be linked, namely the ones from the example.pyx. How do I do this? I do not see any generated .dllor.lib` or similar.

Additionally, if I use #include "exmaple.c" in example.cpp, I get a very long list of missing symbols from the linker. The objects are all named __im_Py*.

I am using MINGW64 on Windows 10. The python installation I am trying to link against is a regular python installation from the system. I have an environment variable CPLUS_INCLUDE_PATH=C:\Program Files\Python310\include.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source