Import C++ function into Python program

后端 未结 5 857
情书的邮戳
情书的邮戳 2020-12-04 21:59

I\'m experimenting with python functions right now. I\'ve found a way to import python functions into c/c++ code, but not the other way around.

I have a c++ program

5条回答
  •  执笔经年
    2020-12-04 22:47

    Here is a little working completion of the simple example above. Although the thread is old, I think it is helpful to have a simple all-embracing guide for beginners, because I also had some problems before.

    function.cpp content (extern "C" used so that ctypes module can handle the function):

    extern "C" int square(int x)
    {
      return x*x;
    }
    

    wrapper.py content:

    import ctypes
    print(ctypes.windll.library.square(4)) # windows
    print(ctypes.CDLL('./library.so').square(4)) # linux or when mingw used on windows
    

    Then compile the function.cpp file (by using mingw for example):

    g++ -shared -c -fPIC function.cpp -o function.o
    

    Then create the shared object library with the following command (note: not everywhere are blanks):

    g++ -shared -Wl,-soname,library.so -o library.so function.o
    

    Then run the wrapper.py an the program should work.

提交回复
热议问题