在 c++ 中使用 pybind11 嵌入 python类:如何调用c++的成员函数来自 python 的类
我有一个具有方法(myClass :: methodwithpy)的课程,可以使用嵌入式pybind11通过某些python脚本来自定义,迄今为止可行。
在Python脚本中,我需要以某种方式调用C ++类的方法。这有可能吗?
这就是我到目前为止的目标,但是我不知道如何从Python中调用类方法。
class MyClass
{
public:
MyClass();
double pureCMethod(double d);
void methodWithPy();
private:
double m_some_member;
};
// method of the c++ class that has acess to members and does some computation
double MyClass::pureCMethod(double d)
{
// here we have some costly computation
return m_some_member*d;
}
// 2nd method of the c++ class that uses embedded python
void MyClass::methodWithPy()
{
namespace py = pybind11;
using namespace py::literals;
py::scoped_interpreter guard{};
py::exec(R"(
print("Hello From Python")
result = 23.0 + 1337
result = MyClass::pureCMethod(reslut) // pseudocode here. how can I do this?
print(result)
)", py::globals());
}
I've a class with a method (MyClass::methodWithPy) that can be customized by some python script using embedded pybind11, which so far works.
Inside the python script I need to somehow call methods of the c++ class. Is this possible somehow?
This is what I have so far, but I do not know how to call the class method from within python.
class MyClass
{
public:
MyClass();
double pureCMethod(double d);
void methodWithPy();
private:
double m_some_member;
};
// method of the c++ class that has acess to members and does some computation
double MyClass::pureCMethod(double d)
{
// here we have some costly computation
return m_some_member*d;
}
// 2nd method of the c++ class that uses embedded python
void MyClass::methodWithPy()
{
namespace py = pybind11;
using namespace py::literals;
py::scoped_interpreter guard{};
py::exec(R"(
print("Hello From Python")
result = 23.0 + 1337
result = MyClass::pureCMethod(reslut) // pseudocode here. how can I do this?
print(result)
)", py::globals());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢@unddoch的链接。那让我得到了答案。
pybind11_embedded_module是我缺少的部分。
首先,您需要定义一个包含类和Methos的嵌入式Python模块:
然后将类传递给Python(首先导入模块)
,现在可以从Python访问成员方法
Thanks @unddoch for the link. That got me to the answer.
PYBIND11_EMBEDDED_MODULE was the part I was missing.
First you need to define an embedded python module containing the class and the methos:
Then pass the class to python (import the module first)
And now its possible to access the member methods from python