简体   繁体   中英

How to return ndarray in python3 ctypes?

I have a c++ function:

double* hiho() {
  double *res = new double[10];
  return res;
}

together with

from numpy.ctypeslib import ndpointer

mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))

When calling the function, I get the following error:

ValueError: '<P' is not a valid PEP 3118 buffer format string

I use Python 3.6.2

What am I doing wrong?

I couldn't reproduce your error, but this works. Provide a reproducible example if this doesn't help you fix it:

test.cpp (Windows)

#define API __declspec(dllexport) // Windows-specific export

extern "C" API double* hiho() {
  double *res = new double[10];
  for(int i = 0; i < 10; ++i)
      res[i] = .1 * i;
  return res;
}

test.py

import ctypes
from numpy.ctypeslib import ndpointer

mylib = ctypes.CDLL('test')
mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))
print(mylib.hiho())

Output

[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

I have updated numpy to version 1.18.1. Now, this works very well :

from numpy.ctypeslib import ndpointer

mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))

To update numpy simply :

pip install numpy --upgrade

For your info :

With numpy 1.15.4, I had the same error with your example Mark with *double or *int.

my compile lines on MacOS :

g++ -c -fPIC -std=c++17 test.cpp -o test.o

g++ -dynamiclib -undefined suppress -flat_namespace test.o -o test.dylib

or

g++ -c test.cpp -o test.o

g++ -dynamiclib -undefined suppress -flat_namespace test.o -o test.dylib

Error :

ValueError: '<P' is not a valid PEP 3118 buffer format string

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