简体   繁体   English

为要在python中使用的c ++库生成包装器代码

[英]Generating wrapper code for a c++ library to be used in python

I am creating a simulation tool in python and require a c++ library. 我正在python中创建一个仿真工具,并且需要一个c ++库。 How do I go about interfacing the library with python? 我该如何与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. 到目前为止,我已经厌倦了在较小的C ++代码上使用ctypes和SWIG,只是为了熟悉该过程。

With ctypes the c++ library must already be compiled into a shared library, which is not a problem. 使用ctypes时,必须已经将c ++库编译为共享库,这不是问题。 I have used ctypes to call c++ function from a shared library but can you use ctypes to call class member functions? 我已经使用ctypes从共享库中调用c ++函数,但是可以使用ctypes来调用类成员函数吗?

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? 如果我使用SWIG,是否必须在接口文件中包含c ++库的所有头文件,还是仅包含包含所需功能的头文件?

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. ctypes可以调用C接口或extern "C" C ++接口,但是它不理解C ++特定的类,例如std::string或成员函数。

With SWIG, you may include only the headers in the SWIG interface file that you want to expose to Python. 使用SWIG,您可以仅在想要公开给Python的SWIG接口文件中包含标头。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM