python - 如何使 C++ 将二维数组返回给 Python

标签 python c++ arrays

我找到一个 example展示如何将一维数组从 C++ 返回到 Python。现在我希望将二维数组从 c++ 返回到 python。 我模仿示例中的代码,我的代码如下:

文件a.cpp:

#include <stdio.h>
#include <stdlib.h>

extern "C" int* ls1(){
    int *ls = new int[3];
    for (int i = 0; i < 3; ++i)
    {
        ls[i] = i;
    }
    return ls;
}
extern "C" int** ls2(){
    int** information = new int*[3];
    int count = 0;
    for (int i = 0; i < 3; ++i)
    {
        information[i] = new int[3];
    }
    for(int k=0;k<3;k++){
        for(int j=0;j<3;j++)
            information[k][j] = count++;
    }
    return information;
}

文件b.py:

import ctypes
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL('./library.so')
lib.ls1.restype = ndpointer(dtype=ctypes.c_int, shape=(3,))
res = lib.ls1()
print 'res of ls1:'
print res

lib.ls2.restype = ndpointer(dtype=ctypes.c_int, shape=(3,3))
res = lib.ls2()
print 'res of ls2:'
print res

我运行以下命令:

g++ -c -fPIC *.cpp -o function.o
g++ -shared -Wl,-soname,library.so -o library.so function.o
python b.py

然后我得到以下打印:

res of ls1:
[0 1 2]
res of ls2:
[[32370416        0 35329168]
 [       0 35329200        0]
 [     481        0 34748352]]

看来我成功地返回了一维数组,就像在 example 中显示的一样.但我无法返回二维数组。我怎样才能让它工作? 谢谢大家帮助我!!!

最佳答案

您分配的数组不正确。

int* 可能指向 1D attay 的开始。

int** never 指向二维数组的开头。它可能指向一维指针数组的开头,每个指针依次指向一维数组的开头。这是一个合法的数据结构,但它不同于二维数组,不兼容 Python 的

ndpointer(dtype=ctypes.c_int, shape=(3,3))

要返回一个真正的二维数组,你可以这样做:

typedef int a3[3];
a3 array[3] = new a3[3];
// no more allocations
for(int k=0;k<3;k++){ ...

请注意,在 C++ 中的二维数组中,除一维之外的所有维度都是固定的。

如果你想返回 Python 可以解释为二维数组的东西,你可以返回一维数组:

int* array = new int[9];
// initialize it

Python 会将其用作 3x3 矩阵就好了。这允许您改变所有数组维度:C++ 永远不知道它是一个二维数组,您只需将所有维度相乘即可。

如果出于某种原因确实需要一个指针数组(不推荐),则需要在 Python 端使用类似这样的东西:

int3type = ndpointer(dtype=ctypes.c_int, shape=(3,))
lib.ls2.restype = ndpointer(dtype=int3type, shape=(3,))

(我不是 ctypes 大师,所以请谨慎对待)。

最后,考虑使用 boost::python。有了它,您可以在 C++ 端正常使用 std::vector,而无需求助于低级 hackery。

关于python - 如何使 C++ 将二维数组返回给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43013870/

相关文章:

javascript - 如何使用 groupBy 函数输出数组

c - 获取字符串直到第一个数字

Python插入二维数组:list index out of range

python - xmltodict unparse 解析不一样

python - 如何在同一个表中的同一个模板上显示来自两个不同 Django 模型的实例?

python - 如何在 Python lambda 表达式中表达条件执行?

c++ - 如何在 CMake 中添加 "-l"(ell) 编译器标志

c++ - 将 std::chrono::time_point 转换为 unix 时间戳

位域结构的 C++ 严格别名规则

arrays - 查找数组的所有元素是否不同的最快方法?