python調用C/C++有不少的方法,如boost.python, swig, ctypes, pybind11等,這些方法有繁有簡,而pybind11的優點是對C++ 11支持很好,API比較簡單,現在我們就簡單記下Pybind11的入門操作。
1. pybind11簡介與環境安裝
pybind11是一個輕量級的只包含頭文件的庫,它主要是用來在已有的 C++代碼的基礎上做擴展,它的語法和目標非常像Boost.Python,但Boost.Python為了兼容現有的基本所有的C++編譯器而變得非常復雜和龐大,而因此付出的代價是很多晦澀的模板技巧以及很多不必要的對舊版編譯器的支持。Pybind11摒棄了這些支持,它只支持python2.7以上以及C++ 11以上的編譯器,使得它比Boost.Python更加簡潔高效。
為了使用pybind11,我們需要支持C++ 11標准的編譯器(GCC 4.8以上,VS 2015 Update 3以上)以及python 2.7以上的版本,還需要下載CMake,有了這些以后,
1. 首先,我們從 pybind11 github網址:https://github.com/pybind/pybind11 上下載源碼。
2. cmake工程之前,要先安裝pytest pip install pytest
,否則會出錯
3. 用CMake編譯並運行測試用例:
mkdir build cd build cmake .. cmake --build . --config Release --target check
如果所有測試用例都通過了,說明安裝成功了。
2. python調用C++
下載編譯好pybind11之后,我們就可以開始對着官方的pybind11 Tutorial進行學習了,詳細的入門教程及語法請參考官方文檔,這里,我們簡單演示下如何編寫供python調用的C++模塊.
首先,我們編寫一個C++源文件,命名為example.cpp
1 #include <pybind11/pybind11.h> 2 namespace py = pybind11; 3 4 int add(int i, int j) 5 { 6 return i + j; 7 } 8 9 PYBIND11_MODULE(example, m) 10 { 11 // optional module docstring 12 m.doc() = "pybind11 example plugin"; 13 // expose add function, and add keyword arguments and default arguments 14 m.def("add", &add, "A function which adds two numbers", py::arg("i")=1, py::arg("j")=2); 15 16 // exporting variables 17 m.attr("the_answer") = 42; 18 py::object world = py::cast("World"); 19 m.attr("what") = world; 20 }
2.1 編譯
然后,在windows下使用工具vs2015 x86 Native Tools Command Prompt
(因為我的python是32位版本,如果是64位版本的,請使用vs2015 x64 Native Tools Command Prompt
)進行編譯:
cl example.cpp /I "H:/Allfiles/pybind11/include" /I "C:/Python27/include" /LD /Fe:example.pyd /link/LIBPATH:"C:/python27/libs/"
編譯成功后,會在example.cpp
相同目錄下生成example.pyd
文件,這個就是python可以直接導入的庫,運行:
1 import example 2 example.add(3, 4) 3 4 [out]: 7
有了編譯成功的模塊,便可以使用我在另一篇博客Python模塊搜索路徑中提到的方法,將其用.pth或者PYTHONPATH的方法加入到python搜索路徑,以后在我們自己的環境中就可以隨時隨地使用這個模塊啦。
2.2 CMake的編譯方法
當然,我們也可以使用CMake進行編譯。首先寫一個CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12) project(example) add_subdirectory(pybind11) pybind11_add_module(example example.cpp)
這里要求example.cpp放在和pybind11同一級的目錄下,然后CMake,便會生成一個vs 2015的工程文件,用vs打開工程文件進行build,就可以生成example.pyd
了。
3. C++調用python
使用pybind11,也很容易從C++里調用python腳本:
首先,我們用vs 2015新建一個工程,並且將Python的包含目錄和庫目錄,以及pybind11的包含目錄配置到工程,我的配置如下:
然后,新建一個源文件example.cpp
:
1 #include <pybind11/embed.h> 2 #include <iostream> 3 4 namespace py = pybind11; 5 6 int main() { 7 py::scoped_interpreter python; 8 9 //py::module sys = py::module::import("sys"); 10 //py::print(sys.attr("path")); 11 12 py::module t = py::module::import("example"); 13 t.attr("add")(1, 2); 14 return 0; 15 }
最后,在工程目錄下加入腳本example.py
:
1 def add(i, j): 2 print("hello, pybind11") 3 return i+j
運行工程,得到如下的結果:
hello, pybind11
運行成功!!!
總結
本文中我們簡單介紹了怎么使用pybind11進行python和C++的相互調用,這些只是入門級別的例子,但是可以work了,這很重要。深入進行研究使用,還是等以后用到再說吧。
參考文獻
原文連接:https://blog.csdn.net/fitzzhang/article/details/78988682