6

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) ));
}
2
  • The initial code works for me. It may be worth verifying that Boost.Python and myModule are being built against the same version of Python, and using the same Boost.Python build configuration. Additionally, verify that myModule links against the Boost.Python version from which it was built against. Sep 6, 2013 at 19:31
  • I think everything uses consistent Python libraries. I checked with Dependency Walker but I might have missed something. I'm using 64-bit Python 2.7.5 and compiling with Mingw-w64 on Windows. I had to use gendef and dlltool to generate libpython27.a from python27.dll. Might that have something to do with this?
    – A_K
    Sep 6, 2013 at 20:38

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.