使用Boost Python公开带有带有数组参数的构造函数的类

Exposing a class with a constructor that has an array argument with Boost Python

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

我正在尝试使用Boost Python导出一个类,看起来像这样:

struct bool_array
{
    bool_array(bool constructor_bool[7])
    {
        for(unsigned int i=0; i < 7; i++)
            bools[i] = constructor_bool[i];
    }
    bool bools[7];
};

我还想公开构造函数,使用以下Boost代码:

class_<bool_array>("bool_array", init<bool*>())
    .def_readwrite("bools", &bool_array::bools)
;

问题是我得到这个编译器错误:

error C2440: '=' : cannot convert from 'const bool [7]' to 'bool [7]'

我也试过

init<bool[7]>

init<bool[]>

to no avail

我确信我错过了一些明显的东西,但是我一直无法弄清楚我需要做什么来公开这个类。

谢谢

在钻研这个问题时,我了解到boost-python不支持直接暴露c风格的数组。相反,我选择使用vector:

struct bool_array
{
    bool_array(std::vector<bool> constructor_bool)
    {
        for(unsigned int i=0; i < 7; i++)
            bools.push_back(constructor_bool[i]);
    }
     std::vector<bool> bools;
};

使用以下boost-python包装器:

typedef std::vector<bool> BoolVector;
bp::class_<BoolVector>("BoolVector")
    .def(bp::vector_indexing_suite<BoolVector>())
;
bp::class_<bool_array>("bool_array", bp::init<std::vector<bool>>())
    .def_readwrite("bools", &bool_array::bools)
;