[英]Construct a numpy array from a C structure using ctypes. ValueError: '<P' is not a valid PEP 3118 buffer format string
考慮以下代碼:
by_ref.h
typedef struct OutPutImage{
double *** output_img;
int nb_images;
int nb_cols;
int nb_rows;
}opi_;
void test_output_images(struct OutPutImage * out, int nb_images, int nb_cols, int nb_rows);
by_ref.c
#include <stdlib.h>
#include "by_ref.h"
void test_output_images(struct OutPutImage* out, int nb_images, int nb_cols, int nb_rows){
out->nb_images = nb_images;
out->nb_cols = nb_cols;
out->nb_rows = nb_rows;
out->output_img = (double***)malloc((nb_images) * sizeof(double**));
for(int i = 0; i < nb_images; i++){
out->output_img[i] = (double**)malloc((nb_cols) * sizeof(double*));
for(int j = 0; j < nb_cols; j++){
out->output_img[i][j] = (double*)malloc((nb_rows) * sizeof(double));
for(int k = 0; k < nb_rows; k++){
out->output_img[i][j][k] = 0;
}
}
}
}
和
by_ref.py
import ctypes
import numpy.ctypeslib as npct
import numpy as np
class OutPutImage(ctypes.Structure):
_fields_ = [('output_img', npct.ndpointer(dtype=np.double, ndim=3)),
('nb_images', ctypes.c_int),
('nb_cols', ctypes.c_int),
('nb_rows', ctypes.c_int)]
_libc = ctypes.CDLL("./by_ref.so")
def __init__(self, nb_images=None, nb_cols=None, nb_rows=None):
self.nb_images = nb_images
self.nb_cols = nb_cols
self.nb_rows = nb_rows
if __name__ == '__main__':
libc_adm = ctypes.CDLL("./by_ref.so")
libc_adm.test_output_images.restype = ctypes.c_int
libc_adm.test_output_images.argtypes = [ctypes.POINTER(OutPutImage), ctypes.c_int,
ctypes.c_int, ctypes.c_int]
output_image = OutPutImage(1, 2, 3)
libc_adm.test_output_images(ctypes.byref(output_image), 4, 5, 6)
print(np.array(output_image.output_img, dtype=np.float)) # error ocures here
當我使用以下 Makefile 制作並運行此代碼時
by_ref: by_ref.so
python by_ref.py
by_ref.so: by_ref.o
gcc -shared -o by_ref.so by_ref.o
by_ref.o: by_ref.c
gcc -c -Wall -fpic by_ref.c -o by_ref.o
我得到錯誤:
Traceback (most recent call last):
File "by_ref.py", line 46, in <module>
print(np.array(output_image.output_img, dtype=np.float))
ValueError: '<P' is not a valid PEP 3118 buffer format string
make: *** [Makefile:2: by_ref] Error 1
我確信test_output_images
正在做它應該做的事情。 但是我無法從結構中的數據構建 numpy 數組。 我該如何做到這一點? 另外,我什么時候釋放 memory? 謝謝。
編輯:
如果我使用np.ctypeslib.as_array(output_image.output_img)
我得到同樣的錯誤:
ValueError: '<P' is not a valid PEP 3118 buffer format string
更新:
如果我使用x = np.ctypeslib.as_array(( ctypes.c_double*array_length ).from_address( ctypes.addressof(output_image.output_img) ))
,其中array_length=nb_images*nb_cols*nb_rows
,那么我避免了上述錯誤,但是新數組 x 包含垃圾,無法重塑。
這是 NumPy 1.15.x 中的一個錯誤。 降級到 1.14.6 或更早版本,或者升級到 1.16.0 或更高版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.