Avión
Avión

Reputation: 8376

How to return a matrix from a C++ function to Python using ctypes

I want to return a matrix from a C++ function to a Python function. I've checked this solution, which is an example for returning an array.

As a example, I want to return a 10x10 array filled of 10's.

function.cpp:

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;
}

The Python code is: wrapper.py

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

For compiling this I use:

g++ -c -fPIC function.cpp -o function.o
g++ -shared -Wl,-soname,library.so -o library.so function.o

If soname doesnt work, use install_name:

g++ -c -fPIC function.cpp -o function.o
g++ -shared -Wl,-install_name,library.so -o library.so function.o

After running the python program, python wrapper.py this is the output im having:
[10 10 10 10 10 10 10 10 10 10]

Only one row of 10 elements. I would like to have the 10x10 matrix. What I'm doing wrong? Thanks in advance.

Upvotes: 1

Views: 979

Answers (1)

J0HN
J0HN

Reputation: 26921

function.cpp:

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

In 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

Upvotes: 2

Related Questions