Boost Python - 用参数包装构造函数

Boost Python - Wrapping constructor with arguments

本文关键字:包装 构造函数 参数 Python Boost      更新时间:2023-10-16

我已经设计了一个cpp共享库,现在我想做一个Python包装器来使用它。一切正常,直到有必要更改在其上添加一个参数的cpp库构造函数。

我想知道如何在包装器中反映此参数,因为下面的代码不再起作用。我对代码进行了一些更改,现在它就像波纹管一样。我几乎可以肯定问题出在这一行

py::class_<Wrapper>("Wrapper", py::init<>())

但我不知道如何在这里添加参数。我试过了

py::class_<Wrapper>("Wrapper", py::init<>(const std::string &param))

还有

py::class_<Wrapper>("Wrapper", py::init<const std::string &param>())

但两者都失败了。

编辑一些评论后,我决定使用(没有参考(

py::class_<Wrapper>("Wrapper", py::init<const std::string param>())

但我仍然有相同的错误消息。

包装器.hpp

#include "mycpplib.hpp"
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <boost/python/dict.hpp>
namespace py = boost::python;
namespace np = boost::python::numpy;
class Wrapper 
{
    public:
        // change: inclusion of the new parameter
        Wrapper(const std::string &param);
        py::dict function1();
};

包装纸.cpp

#include "wrapper.hpp"
namespace py = boost::python;
namespace np = boost::python::numpy;
// change: inclusion of the new parameter
Wrapper::Wrapper(
    const std::string &param) {
    //do something
}
py::dict
Wrapper::function1() {
    //do something
}
BOOST_PYTHON_MODULE(libwrapper)
{
    Py_Initialize();
    np::initialize();
    py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())
        .def("_function1", &Wrapper::function1)
    ;
}

wrapper.py

import libwrapper
class Wrapper(libwrapper.Wrapper):
    # change: inclusion of the new parameter
    def __init__(self, param):
        libwrapper.Wrapper.__init__(self, param)
    def function1(self):
        return self._function1()

错误是:

/path/wrapper.cpp: In function 'void init_module_libwrapper()':
/path/wrapper.cpp:24:69: error: template argument 1 is invalid
py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())
                                                                 ^

重新整理提升文档 (https://www.boost.org/doc/libs/1_68_0/libs/python/doc/html/tutorial/tutorial/exposing.html( 我发现:

py::class_<Wrapper>("Wrapper", py::init<const std::string param1>())

应该这样写:

py::class_<Wrapper>("Wrapper", py::init<const std::string>())

没有参数名称。只是类型