pybind11和numpy進行互動

2022-07-21 21:42:28 字數 1042 閱讀 6759

使用乙個遵循buffer protocol的物件就可以和numpy互動了.

這個buffer_protocol要有哪些東西呢? 要有如下介面:

struct

buffer_info ;

其實就是乙個指向陣列的指標+各個維度的資訊就可以了. 然後我們就可以用指標+偏移來訪問數字中的任意位置上的數字了.

下面是乙個可以跑的例子:

1 #include 2 #include 3

4namespace py =pybind11;

56 py::array_t add_arrays(py::array_t input1, py::array_tinput2)

2930

pybind11_module(test, m)

array_t裡的buf就是乙個相容的介面.

buf中可以得到指標和對應數字的維度資訊.

為了方便我們甚至可以使用eigen當作我們相容numpy的介面:

1 #include 2 #include 3

4 #include 56//

n.b. this would equally work with eigen-types that are not predefined. for example replacing7//

all occurrences of "eigen::matrixxd" with "matd", with the following definition:8//

9//typedef eigen::matrixmatd;

1011 eigen::matrixxd inv(const eigen::matrixxd &xs)

1215

16double det(const eigen::matrixxd &xs)

1720

21namespace py =pybind11;

2223

pybind11_module(example,m)

24

更多參考:

pybind11以及打包學習

最近在看fasttext,看到使用pybind11把c 封裝了一下,然後打包後安裝,python可以直接呼叫,非常方便,有點興趣,手動試了簡單例子,本篇沒啥乾貨,簡單記錄下實現過程。c c 都是用pybind11封裝,可以直接用pip安裝即可,官方給出的入門示例十分簡單 include int ad...

python呼叫c 介面 pybind11

pybind11是乙個將c 介面轉接給python的庫,它支援c 11標準的編譯器。這裡我做了乙個簡單的實驗,主要是驗證將eigen matrixxf型別對映到numpy ndarray型別,這樣就可以在python愉快地呼叫c 函式了。完整 見 首先,python指令碼 usr bin env p...

pybind11使用教程筆記 4 2

當 include,std vector std deque std list std array std set std unordered set and std map std unordered map 和python list,set and dict data structures會自動...