![](/img/trans.png)
[英]How can I pass an "array of integer pointers" to a Function in c library from python
[英]How can I pass a pointer to array of pointers to structs from python
我在Python中使用ctypes,我需要將指針傳遞給指向一些C函數結構的指針數組。 這是結構:
typedef struct {
float x;
float y;
float z;
float radius;
} Sphere;
我具有以下原型的功能:
void render(Sphere** spheres);
在Python中,我為Sphere結構聲明了一個類,並且需要將argtypes設置為render
函數:
lib_render = ctypes.cdll.LoadLibrary('librender.so')
class Sphere(ctypes.Structure):
_fields_ = [('x', ctypes.c_float),
('y', ctypes.c_float),
('z', ctypes.c_float),
('radius', ctypes.c_float)]
render = lib_render.render
render.argtypes = [<cannot find out what needs to be here>]
spheres = numpy.array([Sphere(1, 2.8, 3, 0.5),
Sphere(4.2, 2, 1, 3.2)])
render(spheres)
如何正確傳遞該數組?
我用的不是numpy,但是如果沒有它,下面的方法會起作用。 我假設如果您要傳遞一個指向指針的指針,則該指針列表必須為空終止。
from ctypes import *
class Sphere(Structure):
_fields_ = [('x', c_float),
('y', c_float),
('z', c_float),
('radius', c_float)]
dll = CDLL('test')
dll.render.argtypes = POINTER(POINTER(Sphere)),
dll.render.restype = None
# Create a couple of objects
a = Sphere(1,2,3,4)
b = Sphere(5,6,7,8)
# build a list of pointers, null-terminated.
c = (POINTER(Sphere) * 3)(pointer(a),pointer(b),None)
dll.render(c)
測試DLL:
#include <stdio.h>
typedef struct Sphere {
float x;
float y;
float z;
float radius;
} Sphere;
__declspec(dllexport) void render(Sphere** spheres)
{
for(;*spheres;++spheres)
printf("%f %f %f %f\n",(*spheres)->x,(*spheres)->y,(*spheres)->z,(*spheres)->radius);
}
輸出:
1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000
使用numpy
,使用void render(Sphere* spheres, size_t len)
可以正常工作。 如果可以支持Sphere**
也許更熟悉numpy的人可以發表評論。
from ctypes import *
import numpy as np
class Sphere(Structure):
_fields_ = [('x', c_float),
('y', c_float),
('z', c_float),
('radius', c_float)]
dll = CDLL('test')
dll.render.argtypes = POINTER(Sphere),c_size_t
dll.render.restype = None
a = Sphere(1,2,3,4)
b = Sphere(5,6,7,8)
# c = (Sphere * 2)(a,b)
# dll.render(c,len(c))
d = np.array([a,b])
dll.render(d.ctypes.data_as(POINTER(Sphere)),len(d))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.