将 C++ 代码转换为 Python 的 SWIG,这是将 std::array 包装为与 C 样式数组相同的有效方法吗?

问题描述 投票:0回答:1

SWIG 新手在这里。假设我为 C 样式数组定义了一些类型映射:

%typemap(in) double[ANY] (double temp[$1_dim0]) {
  ...
}

// Convert from C to Python for c-style arrays
%typemap(out) double [ANY] {
    ...
}

如果我想让它们对 std::array of double 而不是 C 风格的数组使用同样的逻辑。但是,我不确定将此类型映射应用于任意维度数组的正确语法是什么。以下逻辑是否足够?

%apply double[ANY] { std::array<double, ANY> };

谢谢!

python c++ arrays swig
1个回答
0
投票

SWIG 支持一些 C++ 模板,包括

std::array
,但必须声明接口中使用的每个模板实例。例如:

test.i

%module test

%{
#include <array>
%}

%include <std_array.i>
%template() std::array<double, 10>;
%template() std::array<double, 5>;

%inline %{
double func(const std::array<double, 10>& arr) {
    double sum = 0.0;
    for(auto n: arr)
        sum += n;
    return sum;
}

std::array<double, 5> outfunc() {
    return {5, 4, 3, 2, 1};
}
%}

Python演示:

>>> import test
>>> test.func([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
55.0
>>> test.outfunc()
(5.0, 4.0, 3.0, 2.0, 1.0)
© www.soinside.com 2019 - 2024. All rights reserved.