这是你的名字示例.cpp代码:
#include
namespace py = pybind11;
int add(int i, int j) {
return i + j;
}
class mycl{
public:
mycl(){};
mycl(int a){
age = a;
};
void call(){
printf("I'm here!\n");
}
int ask_age(){
printf("my age is %d\n", age);
}
private:
int age;
};
class mycl myclv;
class mycl *pmycl = &myclv;
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
using namespace pybind11::literals;
m.def("add", &add, //"A function which adds two numbers",
"i"_a, "j"_a);
//py::arg("i"), py::arg("j"));
py::object omycl = py::cast("Pointer to mycl");
m.attr("ptr") = omycl;
py::class_(m, "mycl")
.def(py::init())
.def("AskAge",&mycl::ask_age);
}
我编译如下(这里有pybind11模块):
c++ -std=c++11 example.cpp -fPIC -shared `python3 -m pybind11 --include` -o example.so
下面是python3执行结果:
ckim@chan-ubuntu:~/PYBIND11/pybind11$ python3
Python 3.5.2 (default, Jul 17 2020, 14:04:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> a = example.mycl(53)
>>> a.AskAge()
my age is 53
13
>>> b = example.mycl(54)
>>> b.AskAge()
my age is 54
13
>>>
我不知道在哪里
13
是从哪里来的。有什么问题?
本文通过一个具体的cpp文件示例介绍了如何使用pybind11将C++类和函数暴露给Python,并展示了编译和运行的过程。针对示例中出现的疑问进行了探讨。
1022

被折叠的 条评论
为什么被折叠?



