I am creating a simulation tool in python and require a c++ library. How do I go about interfacing the library with python? The library is large but I only want to call a few functions and class member functions.
So far I have tired using ctypes and SWIG on smaller bits of c++ code just to familiarize myself with the process.
With ctypes the c++ library must already be compiled into a shared library, which is not a problem. I have used ctypes to call c++ function from a shared library but can you use ctypes to call class member functions?
If I use SWIG must I include all the header files of the c++ library in the interface file or only the ones that include the function I need?
ctypes
can call C interfaces, or C++ interfaces that are extern "C"
, but it does not understand C++-specific classes such as std::string
or member functions.
With SWIG, you may include only the headers in the SWIG interface file that you want to expose to Python. For example:
%module example
%{
// This section is copied into the wrapper so the generated code can compile.
// No wrappers are generated from this.
#include "myheader1.h"
#include "myheader2.h"
%}
%include "myheader1.h" // Wrap all functions directly declared in this header.
int myfunc(int a, int b); // Wrap only this one function in myheader2.h.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.