Import C++ function into Python program

后端 未结 5 846
情书的邮戳
情书的邮戳 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:33

    You want to extend python with a C/C++ module. The following Python documentation is a good place to start reading: http://docs.python.org/extending/extending.html

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 22:52

    You need to create a python module with that function in it. There are three main ways:

    1. Using Swig - this reads your c code and creates a python module from it.
    2. Hand coded using the python c api.
    3. Using Boost::Python (often the easiest way).

    This pdf covers 1 and 2. This page will tell you how to use Boost::Python.

    You cannot (easily) use a function that is in a c/c++ program - it must be in a static library (which you can also link your c/c++ program against).

    EDIT - Cython Is also worth a mention.

    0 讨论(0)
  • 2020-12-04 22:54

    If you build your program as a shared library/DLL, you could use ctypes to call it.

    import ctypes
    print ctypes.windll.cprog.square(4) # windows
    print ctypes.CDLL('cprog.so').square(4) # linux
    
    0 讨论(0)
  • 2020-12-04 22:58

    There are a lot of different ways to wrap C++ code to be used in Python. Most are listed on the Python wiki here.

    I've found a decently easy way to automate it is to use py++ to automatically generate the wrappers, then compile the generated files. But this is more appropriate for larger projects where wrapping everything by hand is just not very feasible and would cause a maintenence nightmare.

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