系列文章
【pybind11笔记】eigen与numpy数据交互
【pybind11笔记】python调用c++函数
【pybind11笔记】python调用c++结构体
【pybind11笔记】python调用c++类
文件结构
为了方便演示,我们使用cmake构建该样例,文件结构如下:
pybind11与eigen3这两个文件夹为对应的资源库,不一定需要放置在该项目当中,这里是为了减少对编译环境的依赖,同时在window下更容易编译。
文件内容
创建一个头文件pybind11_eigen.h
,内容如下
#include <pybind11/pybind11.h>
#include <iostream>
#include <pybind11/eigen.h>using namespace std;
namespace py=pybind11;typedef Eigen::Matrix<float, 3, 3> Mat3;
typedef Eigen::Matrix<float, 3, 1> Vec3;Mat3 crossMatrix(Vec3 v);PYBIND11_MODULE(pybind11_eigen, m) {m.def("cross_matrix", &crossMatrix);}
与源文件pybind11_eigen.cpp
#include "pybind11_eigen.h"Mat3 crossMatrix(Vec3 v) {Mat3 m;m << 0, -v[2], v[1],v[2], 0, -v[0],-v[1], v[0], 0;return m;
}
CMakeLists.txt
文件
cmake_minimum_required(VERSION 2.8.9)
project(pybind_eigen_test)
set(CMAKE_CXX_STANDARD 11)# 设置头文件&相关库
include_directories(include)
include_directories(eigen3) add_subdirectory(pybind11)# 模块
pybind11_add_module(pybind11_eigen ./src/pybind11_eigen.cpp)
编译测试
mkdir build
cd build
cmake ..
make
视编译环境可能得用
cmake -G "MinGW Makefile" ..
或者cmake -G "Unix Makefile" ..
我们在ipython环境下进行测试:
$ipython
Python 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.In [1]: from pybind11_eigen import *In [2]: import numpy as npIn [3]:
导入模块没有问题,接下来我们测试功能函数
In [3]: a = np.array([1,2,3])In [4]: b = cross_matrix(a)In [5]: a
Out[5]: array([1, 2, 3])In [6]: b
Out[6]:
array([[ 0., -3., 2.],[ 3., 0., -1.],[-2., 1., 0.]], dtype=float32)In [7]: