简体   繁体   中英

How to pass numpy ndarrays to a c++ function using ctypes?

I spent two days to figure out how to pass ndarrays to c/c++, and still didn't find anything that works correctly.
Every thing is documented awfully and confusing.
The only tutorial that I found is in https://scipy.github.io/old-wiki/pages/C%2B%2B_Extensions_that_use_NumPy_arrays.html .
But when I try to run the python code "myextension.py" it raises ImportError: No module named numpyndarrays.

I don't want to use cython or boost or python C-API.

Here is my c++ code "n.cpp" which I compiled to a shared library:

#include <iostream>
#include "ndarray.h"

extern "C" {

Ndarray<double, 3> myfunc(numpyArray<double> array1)
{
    Ndarray<double,3> a(array1);
    std::cout<<a.getShape(0); //this prints 0 and it means somthing is wrong

    for (int i = 0; i < a.getShape(0); i++)
    {
        for (int j = 0; j < a.getShape(1); j++)
        {
            for (int k = 0; k < a.getShape(2); k++)
            {
                a[i][j][k] = 2.0 * a[i][j][k];
                std::cout<<a[i][j][k]<<' '<<i<<' '<<j<<' '<<k<<'\n';// prints nothing because a.getShape(0) is 0.
            }
        }
    }
    return a;
}
}

At first, when I tried to compile this code, compiler raised fatal error cause it couldn't find ndarray.h.
I manually downloaded the ndarray.h file from https://scipy.github.io/old-wiki/pages/ndarray2e5c.h?action=AttachFile&do=get&target=ndarray.h

Here is my python code:

import numpy as np
import numpy.ctypeslib as ct

mylib = ct.load_library('n', '.')       

def myfunc(array1):
    return mylib.myfunc(array1.ctypes) # I also tried ct.as_ctypes(array1) instead of array1.ctypes with no success

a = np.ones((2,2,2)).astype(np.double)

myfunc(a)

This code loads shared library correctly, the main problem is how to convert numpy ndarray to the structure which is the input for the shared library.
I also need to know, how to convert the output from shared library to numpy ndarray.

I found that using the numpy C-API is the easiest way to pass numpy arrays to c++.
The documentation could be found on https://docs.scipy.org/doc/numpy/reference/c-api.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM