0

I have this c++ code:

#define DLLEXPORT extern "C"

DLLEXPORT double **points(unsigned N, unsigned D)
{

double **POINTS = new double * [N];
for (unsigned i=0;i<=N-1;i++) POINTS[i] = new double [D];
for (unsigned j=0;j<=D-1;j++) POINTS[0][j] = 0;

// do some calculations, f.e:
// POINTS[i][j] = do_smth()
//


return POINTS
}

which I compile using this command:

g++ -shared gpoints.cc -o gpoints.so -fPIC

Now I want to call this function from python using ctypes. I tried smth like this:

mydll = ctypes.cdll.LoadLibrary('/.gpoints.so')
func = mydll.points
mytype = c.c_double * 3 * 10
func.restype = mytype
arr = func(10, 3)
print(arr)

When I try to run it I get:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
[1]    2794 abort      python3 test.py

So, how to properly call this function from Python?

P.S. I got this library "as is", so, it is desirable to use it without rewriting c++ code.

1 Answer 1

1

Your restype is equivalent to double[10][3], but what it actually returns is double**:

#!python3.6
import ctypes as c
dll = c.CDLL('test')
dll.points.argtypes = c.c_int,c.c_int
dll.points.restype = c.POINTER(c.POINTER(c.c_double))
arr = dll.points(10,3)
for i in range(10):
    for j in range(3):
        print(f'({i},{j}) = {arr[i][j]}')

I used the following DLL code to test (Windows):

extern "C" __declspec(dllexport)
double **points(unsigned N, unsigned D)
{
    double **POINTS = new double * [N];
    for (unsigned i=0;i<=N-1;i++)
    {
        POINTS[i] = new double [D];
        for(unsigned j=0;j<=D-1;j++)
            POINTS[i][j] = i*N+j;
    }
    return POINTS;
}

Output:

(0,0) = 0.0
(0,1) = 1.0
(0,2) = 2.0
(1,0) = 10.0
(1,1) = 11.0
(1,2) = 12.0
(2,0) = 20.0
(2,1) = 21.0
   :
Sign up to request clarification or add additional context in comments.

1 Comment

It's awsome! Why manual does not contain such clear examples. I spent a lot of time on this problem. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.