使用Boost库将浮点值列表从Python转换为C ++向量<float>

时间:2018-04-10 07:21:32

标签: python c++ boost boost-python

我正在将浮点值列表从python转换为C ++,并且值未正确转换。例如。如果python中的列表包含以下值 值= [4.2,2.5,3.6,1,0,6.3] 当使用Boost转换为c ++向量时,我得到如下的值, [4.2000004,2.49999998,5.29999998,6.0999998,1,0,6.30000004],虽然我希望将确切的值转换为C ++对象

我使用以下C ++代码转换值

struct iterable_converter
{

template <typename Container>
iterable_converter&
    from_python()
{
    boost::python::converter::registry::push_back(
        &iterable_converter::convertible,
        &iterable_converter::construct<Container>,
        boost::python::type_id<Container>());
    return *this;
}

static void* convertible(PyObject* object)
{
    return PyObject_GetIter(object) ? object : NULL;
}

template <typename Container>
static void construct(
    PyObject* object,
    boost::python::converter::rvalue_from_python_stage1_data* data)
{
    namespace python = boost::python;
    // Object is a borrowed reference, so create a handle indicting it is
    // borrowed for proper reference counting.
    python::handle<> handle(python::borrowed(object));

    // Obtain a handle to the memory block that the converter has allocated
    // for the C++ type.
    typedef python::converter::rvalue_from_python_storage<Container>
        storage_type;
    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;

    typedef python::stl_input_iterator<typename Container::value_type>
        iterator;

    // Allocate the C++ type into the converter's memory block, and assign
    // its handle to the converter's convertible variable.  The C++
    // container is populated by passing the begin and end iterators of
    // the python object to the container's constructor.
    new (storage)Container(
        iterator(python::object(handle)), // begin
        iterator());                      // end
    data->convertible = storage;
}};

并声明下面的类,

iterable_converter()
    .from_python<std::vector<float> >();

在python am中设置如下的值,

a.f_values = [1,2,3,4.2]

但转换后的C ++向量值为[1,2,3,4.19999981]

请帮我解决这个问题

0 个答案:

没有答案