I find an example showing how to return a 1D array from c++ to python. Now I hope to return a 2D array from c++ to python. I imitate the code shown in the example and my code is as follows:
The file 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;
}
The file 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
I run the following commands:
g++ -c -fPIC *.cpp -o function.o
g++ -shared -Wl,-soname,library.so -o library.so function.o
python b.py
Then I get the following prints:
res of ls1:
[0 1 2]
res of ls2:
[[32370416 0 35329168]
[ 0 35329200 0]
[ 481 0 34748352]]
It seems I succeed in returning 1D array, just in the same way shown in the example. But I fail in returning 2D array. How can I get it work? Thank you all for helping me!!!
new int [9]