Calling C++ code from Python using Cython whith the distutilis approach

后端 未结 1 1863
故里飘歌
故里飘歌 2021-02-06 17:24

I am trying to call a c++ code from a python script using cython. I already managed to work with an example from here but the thing is: my c++ code includes non-standard librari

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 18:00

    Resolved, thanks to Dietmar Kühl's comments and this video from youtube!

    What was wrong? I found out that my setup.py was misconfigured. It should be like:

    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Distutils import build_ext
    
    setup(
        name = 'DyCppInterface',
        version = '1.0',
        author = 'Marcelo Salloum dos Santos',
        # The ext modules interface the cpp code with the python one:
        ext_modules=[
            Extension("rectangle",
                sources=["rectangle.pyx", "cpp_rect.cpp"], # Note, you can link against a c++ library instead of including the source
                include_dirs=[".","source" , "/opt/local/include/opencv", "/opt/local/include"],
                language="c++",
                library_dirs=['/opt/local/lib', 'source'],
                libraries=['opencv_core', 'LibCppOpenCV'])
        ],
        cmdclass = {'build_ext': build_ext},
    )
    

    The three things to pay attention in order to correctly configure it are:

    • include_dirs: each referenced file in the setup.py or the .h and .cpp shall have its container folder in the include_dirs;
    • library_dirs: each referenced library shall have its container folder written here;
    • libraries: one MUST put the library's name here

    Further questions on how to configure a library for cython can be answered by watching this video on how to use and configure a dynamic library (using Eclipse CDT).

    0 讨论(0)
提交回复
热议问题