Emi*_* D. 7 c++ python pybind11
我使用 pybind11 作为 C++ 代码到 python 库的包装器。
碰巧有些参数我无法提供,或者有时我想进行我在 C++ 方面知道的转换/初始化。例如,这可能是因为该类在 python 中是未知的。怎么可能呢?到目前为止,我看到的唯一“解决方案”是在 C++ 中创建一个继承的代理类。
示例:我想定义/绑定一个 python 类 A:
class A:
def __init__(self, B b):
...
Run Code Online (Sandbox Code Playgroud)
使用 C++ 等效类:
class A {
A(C c, D d);
}
Run Code Online (Sandbox Code Playgroud)
我可以为 pybind11::init<> 创建某种 lambda 或等效函数吗?
pybind11 允许您将工厂函数绑定为 init 方法。因此,您必须在 C++ 中提供一个接受 B 并返回 A 的函数,然后您可以将其绑定为 A 的 init 方法。
pybind11 文档中的示例
class Example {
private:
Example(int); // private constructor
public:
// Factory function:
static Example create(int a) { return Example(a); }
};
py::class_<Example>(m, "Example")
.def(py::init(&Example::create));
Run Code Online (Sandbox Code Playgroud)
如果您不想(或不能)更改 C++ 中的类 A,您也应该能够绑定自由函数(而不仅仅是静态函数)。
所以它可能看起来像这样(更改为返回一个 unique_ptr,pybind 可以只获取原始实例的所有权。但两者都应该有效)
std::unique_ptr<A> createA(const B& arg)
{
// returns an instance of A that you made using B
}
py::class_<A>(m, "A")
.def(py::init(&createA));
Run Code Online (Sandbox Code Playgroud)
显然,您还必须在 python 中为 B 提供绑定。
文档在这里,包括更多示例,包括如何执行 init lambda: https ://pybind11.readthedocs.io/en/stable/advanced/classes.html#custom-constructors