将指针从C ++传递给Python / w boost python?

时间:2013-09-05 22:03:08

标签: c++ python boost boost-python

我正在使用Boost Python,我在C ++中生成一个大的整数向量,我想在Python中访问这个向量而不复制它。

在C ++中我有:

BOOST_PYTHON_MODULE(myModule)
{
    class_<vector<int>>("vectorInt").def(vector_indexing_suite<vector<int>>());
    def("ReturnVectorPtr", ReturnVectorPtr, return_value_policy<manage_new_object>());
}

vector<int>* ReturnVectorPtr()
{
    return new vector<int>();
}

然后在python中我有:

import myModule
myModule.ReturnVectorPtr()

这导致Python崩溃,尽管我甚至没有存储返回值。关于我的错误是什么想法?

编辑:

以下代码用于将向量中的数据从C ++传递到python,但泄漏内存。是否复制了矢量,然后没有处理?

在C ++中:

BOOST_PYTHON_MODULE(myModule)
{
    class_<vector<int>>("vectorInt").def(vector_indexing_suite<vector<int>>());
    def("ModifyVectorInPlace", ModifyVectorInPlace);
}

void ModifyVectorInPlace(vector<int>& data)
{
    // Modify data...
    return;
}

然后在python中我有:

import myModule
vectorInt = myModule.vectorInt()
myModule.ModifyVectorInPlace(vectorInt)

发生了什么事?

编辑2:

我尝试过&#34; Raw C ++ Pointers&#34;这里的例子,完全如下: https://wiki.python.org/moin/boost.python/PointersAndSmartPointers

它也崩溃了。似乎我无法获得指向任何传递给Python的东西的指针......

编辑3:

崩溃似乎是来自invoke.hpp的段错误,在此函数中:

template <class RC, class F BOOST_PP_ENUM_TRAILING_PARAMS_Z(1, N, class AC)>
inline PyObject* invoke(invoke_tag_<false,false>, RC const& rc, F& f BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(1, N, AC, & ac) )
{
    return rc(f( BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, ac, () BOOST_PP_INTERCEPT) ));
}

1 个答案:

答案 0 :(得分:0)

事实证明,这是Mingw-w64和Python之间交互的一个错误。我执行了这里描述的程序,问题解决了:

http://ascend4.org/Setting_up_a_MinGW-w64_build_environment#Setup_Python_for_compilation_of_extensions