首页 > 解决方案 > Boost Python - 用参数包装构造函数

问题描述

我已经设计了一个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)
    ;
}

包装器.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>())
                                                                 ^

标签: pythonc++wrapperboost-python

解决方案


阅读 boost 文档(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>())

没有参数名称。只是类型


推荐阅读