lang:c:pybind11
文書の過去の版を表示しています。
pybind11
C/C++ のコードを python で利用する。
個人的には、boost よりも使いやすい。
基本
- exPybind11.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <pybind11/pybind11.h> void functionInPython(void){ std::cout << "call functionInCPP\n"; } class ClassInCpp { public: ClassInCpp(void) : varInClassInCpp("varInClassInCpp"){ } std::string varInClassInCpp ; void functionClassInCpp(void){ std::cout << "call functionClassInCpp\n"; } template <typename TT1> TT1 templateFunctionInCpp(TT1 x){ std::cout << "call templateFunctionInCpp -arg= " << x << "\n"; return x * x; } }; PYBIND11_MODULE(examplePybind11, m) { m.def("functionInPython", &functionInPython); pybind11::class_<ClassInCpp>(m, "classInPython") .def(pybind11::init<>()) .def_readwrite("varInPython", &ClassInCpp::varInClassInCpp) .def("functionClassInPython", &ClassInCpp::functionClassInCpp) // template function .def("templateFunctionInPython", (uint64_t (ClassInCpp::*)(uint64_t)) &ClassInCpp::templateFunctionInCpp) .def("templateFunctionInPython", (float (ClassInCpp::*)(float )) &ClassInCpp::templateFunctionInCpp); }
complile
c++ exPybind11.cpp -o examplePybind11.so -std=c++11 -shared -fPIC \ -I"pybindIncludeDir" \ `/usr/bin/python3-config --cflags --ldflags`
ここで、examplePybind11.so の prefix (“.so” を除外した部分) は、
“PYBIND11_MODULE(examplePybind11, m)” の第一引数と同じこと。
python での使用方法
- example.py
import os import sys import examplePybind11 examplePybind11.functionInPython() c = examplePybind11.classInPython() print(c.varInPython) c.functionClassInPython() v = c.templateFunctionInPython(2) print (v) v = c.templateFunctionInPython(1.1) print (v)
list の使用
- list.cpp
void func(pybind11:list pylist){ for (uint64_t i=0; i<pylist.size(); i++){ pybind11::handle item = pylist[i]; std::string x = item.cast<std::string>(); } }
lang/c/pybind11.1756033574.txt.gz · 最終更新: by editor