【问题标题】:Pass pointer from C++ to Python /w boost python?将指针从 C++ 传递到 Python /w boost python?
【发布时间】:2013-09-05 22:03:07
【问题描述】:

我正在使用 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:

我从这里尝试了“原始 C++ 指针”示例,完全按照所写: 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) ));
}

【问题讨论】:

  • 初始代码对我有用。可能值得验证 Boost.Python 和 myModule 是针对相同版本的 Python 构建的,并使用相同的 Boost.Python 构建配置。此外,验证 myModule 是否与构建它的 Boost.Python 版本相关联。
  • 我认为一切都使用一致的 Python 库。我检查了 Dependency Walker,但我可能错过了一些东西。我正在使用 64 位 Python 2.7.5 并在 Windows 上使用 Mingw-w64 进行编译。我不得不使用 gendef 和 dlltool 从 python27.dll 生成 libpython27.a。这可能与此有关吗?

标签: c++ python boost boost-python


【解决方案1】:

原来这是 Mingw-w64 和 Python 之间交互的一个错误。我执行了这里描述的过程,问题就解决了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2020-08-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多