pybind通常是使用c++调用python文件,创建一个名为test_basic.py的文件,下面叙述调用步骤:
1.c++调用python:
def test_main():
print("hello python.")
def test_func2(a):
print(type(a))
a.print()
2.python调用c++,其实原理就是c++调用python再hook回去cpp代码,传给python的参数是一个对象(可以是指针,对象也可以),对象内部包含这cpp的函数,在python层的方法里面,调用cpp的方法即可。
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/embed.h>
#define STRINGIFY(x) #x
#define MACRO_STRINGIFY(x) STRINGIFY(x)
class A
{
public:
A() {}
double a;
void print();
};
void A::print()
{
printf("hello A.\n");
}
namespace py = pybind11;
PYBIND11_EMBEDDED_MODULE(embeded, module)
{
py::class_<A> a(module, "A");
a.def("print", &A::print);
}
int main()
{
py::scoped_interpreter python;
auto test = py::module::import("tests.test_basic");
auto embeded = py::module::import("embeded");
// auto func = test.attr("test_main");
py::object result;
// result = func();
auto func2 = test.attr("test_func2");
// auto a = new A();
auto a = A();
// auto func_a = []()
// { printf("hello anonymous function.\n"); };
a.a = 1.0;
result = func2(a);
}```