简体   繁体   中英

Pass pointer from C++ to Python /w boost python?

I am using Boost Python, I generate a large vector of integers in C++, and I would like to access this vector in Python without copying it.

In C++ I have:

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>();
}

Then in python I have:

import myModule
myModule.ReturnVectorPtr()

This causes Python to crash, although I'm not even storing the return value. Any ideas on what my mistake is?

Edit:

The following code works for getting the data in the vector from C++ to python, but leaks memory. Are the vectors being copied and then not disposed?

In 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;
}

Then in python I have:

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

What is going on?

Edit 2:

I tried the "Raw C++ Pointers" example from here, exactly as written: https://wiki.python.org/moin/boost.python/PointersAndSmartPointers

It crashes too. It seems that I can't get a pointer to anything passed into Python for some reason...

Edit 3:

The crash appears to be a segfault from invoke.hpp, in this function:

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) ));
}

It turns out this was a bug in the interaction between Mingw-w64 and Python. I performed the procedure described here and the problem was solved:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM