从 Python 调用 C++ 基本上有两种方法:一是使用 PyBind11 C++ 库生成 Python 模块,二使用 cytpes Python 包访问已编译的共享库。 使用cytpes还需要额外对c++代码进行处理,而使用 Pybind11能够直接对c++代码进行导出,并且支持c++的许多数据类型如vector的自动转换,十分方便。
安装的教程很多,在此不再赘述。然而,对一个新手来说, 难免在使用的时候会遇到很多坑,而有些坑比较玄学,本教程也只是记录遇到过的一些坑的解决办法,便于自己回顾类似的问题,如果能顺便帮助到其他人,不上荣幸。
注意:本文只适用于ubuntu系统
Example:
将c++代码导出为python接口至少需要两个文件,源文件和cmakelists.txt文件,假设都在example文件下:
1. 源文件,需要包含c++代码和pybind11的接口绑定:
pybind_test.cpp
#include <pybind11/pybind11.h>
#include <string>
#include <iostream>
using namespace std;
namespace py = pybind11;
class Pybindtest
{
public:
virtual ~Pybindtest();
Pybindtest(std::string &inputs)
{
info = inputs;
}
void printInfo()
{
std::cout << "Your input is " << info << std::endl;
}
private:
std::string info;
};
PYBIND11_MODULE(libmy_module, m)
{
m.doc() = "pybind11 Hierarchical Localization cpp backend";
py::class_<Pybindtest>(m, "Pybindtest")
.def(py::init<std::string &>())
.def("printInfo", &Pybindtest::printInfo);
}
2.CMakeLists.txt
cmake_minimum_required(VERSI