从C ++实例化包装器类

时间:2019-01-21 11:08:18

标签: c++ pybind11

我使用pybind11包装了一个简单的c ++接口/类

public function add($tasktypeid)
{   
    $this->autoRender = false; //no need for view

    debug($this->request->data());
    if($this->request->is('post'))
    {
        debug($this->request->data());
    }

}

IBaseObject是接口,SmartPtr是自定义持有人类型,BaseObject_Create是工厂函数,它返回IBaseObject *。

从python实例化类工作正常,但是我还想在将IBaseObject *作为参数传递时实例化C ++的python包装类。这可能吗?

1 个答案:

答案 0 :(得分:0)

如果只想在C ++绑定代码中实例化类,则可以使用pybind的Python C ++接口:

https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html#calling-python-functions

某些方法可以做到这一点:

// Option 1: Use your existing class handle.
py::class_<IBaseObject, ...> py_cls(...);
py::object py_obj = py_cls();
// - Cast it if you need to.
auto* obj = py_obj.cast<IBaseObject*>();
// - or cast to `SmartPtr<IBaseObject>()` if its shareable.

// Option 2: Re-import elsewhere in your code.
py::object py_cls = py::module::import("my_pybind_module").attr("IBaseObject");
py::object py_obj = py_cls();
// - etc...

// Option 3: Use `eval` (blech)
py::module m = py::module::import("my_pybind_module");
py::object py_obj = py::eval("IBaseObject()", /* globals */ m.attr("__dict__"));
相关问题