您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

SWIG包装的向量载体(从C ++到python)-如何将内部向量识别为代理对象?

SWIG包装的向量载体(从C ++到python)-如何将内部向量识别为代理对象?

我曾与我的一位同事合作过,我们设法提出了一些解决方案。

首先,在SWIG .i文件中,定义此预处理器变量很重要:

%{
#   define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS 
%}

然后,为了确保从诸如front(),back(),operator []等方法返回的引用实际上已映射到内部向量的正确代理类型,以下类型映射帮助:

// In pop()
%typemap(out) std::vector<std::vector<ns::uint64_t> >::value_type { 
$result = SWIG_NewPointerObj(SWIG_as_voidptr(&$1), $descriptor(std::vector<ns::uint64_t>), 0 |  0 ); 
}

// In front(), back(), __getitem__()
%typemap(out) std::vector<std::vector<ns::uint64_t> >::value_type & { 
    $result = SWIG_NewPointerObj(SWIG_as_voidptr($1), $descriptor(std::vector<ns::uint64_t>), 0 |  0 ); 
}

我们还发现,如果您想将ns :: uint64_t视为python long变量(等效于C unsigned long long),则还需要一些其他类型映射,以确保使用值和引用的矢量方法仅使用64位整数值。

// In __getitem__()
%typemap(out) ns::uint64_t {
    $result = PyLong_FromUnsignedLongLong($1);
}
// Not used (but probably useful to have, just in case)
%typemap(in) ns::uint64_t {
    $1 = PyLong_AsUnsignedLongLong($input);
}
// In pop()
%typemap(out) std::vector<ns::uint64_t>::value_type {
    $result = PyLong_FromUnsignedLongLong($1);
}
// In __getitem__(), front(), back()
%typemap(out) std::vector<ns::uint64_t>::value_type & {
    $result = PyLong_FromUnsignedLongLong(*$1);
}
// In __setitem__(), append(), new Uint64Vector, push_back(), assign(), resize(), insert()
// This allows a python long literal number to be used as a parameter to the above methods. 
// Note the use of a local variable declared at the SWIG wrapper function scope,
// by placing the variable declaration in parentheses () prior to the open brace {
%typemap(in) std::vector<ns::uint64_t>::value_type & (std::vector<ns::uint64_t>::value_type temp) {
    temp = PyLong_AsUnsignedLongLong($input);
    $1 = &temp;
}

我希望这种解决方案将来对人们有所帮助!

python 2022/1/1 18:30:54 有322人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶