如何使用ctypes将矩阵从C ++函数返回到Python

时间:2013-10-01 09:53:43

标签: c++ python ctypes

我想将一个矩阵从C ++函数返回到Python函数。我检查了this解决方案,这是返回数组的一个例子。

例如,我想返回一个填充10x10的{​​{1}}数组。

function.cpp:

10

Python代码是: 的 wrapper.py

extern "C" int* function(){
int** information = new int*[10];
for(int k=0;k<10;k++) {
    information[k] = new int[10];
    }
for(int k=0;k<10;k++) {
    for(int l=0;l<10;l++) {
        information[k][l] = 10;
        }
}
return *information;
}

为了编译这个,我使用:

import ctypes
from numpy.ctypeslib import ndpointer

lib = ctypes.CDLL('./library.so')
lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,))

res = lib.function()
print res

如果g++ -c -fPIC function.cpp -o function.o g++ -shared -Wl,-soname,library.so -o library.so function.o 不起作用,请使用soname

install_name

运行python程序后,g++ -c -fPIC function.cpp -o function.o g++ -shared -Wl,-install_name,library.so -o library.so function.o 这是输出即时消息:
python wrapper.py

只有一行10个元素。我想要10x10矩阵。我做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分:2)

function.cpp

extern "C" int* function(){
    int* result = new int[100];
    for(int k=0;k<100;k++) {
        result[k] = 10;
    }
    return result;
}

wrapper.py

lib.function.restype = ndpointer(dtype=ctypes.c_int, shape=(10,)) //incorrect shape
lib.function.restype = ndpointer(dtype=ctypes.c_int, ndim=2, shape=(10,10)) // Should be two-dimensional