我需要使用共享库(.so)处理从 C 程序到 python 实例(Django)的大量数据。 是否可以通过 ctypes 返回它们?
例如:
import ctypes
a = ctypes.CDLL('foo.so')
b = a.collect()
latitude = b.latitude
longitude = b.longitude
和一个C:
main()
{
/* steps to get the data */
return <kind of struct or smth else>;
}
我是新手,有没有办法传递此类数据?
最佳答案
一种选择是通过指针参数返回值:
// c
void collect(int* outLatitude, int* outLongitude) {
*outLatitude = 10;
*outLongitude = 20;
}
和
# python
x = ctypes.c_int()
y = ctypes.c_int()
library.collect(ctypes.byref(x), ctypes.byref(y))
print x.value, y.value
<小时/>
如果您需要更多,您可以返回一个结构:
// c
typedef struct {
int latitude, longitude;
} Location;
Location collect();
和
# python
class Location(ctypes.Structure):
_fields_ = [('latitude', ctypes.c_int), ('longitude', ctypes.c_int)]
library.collect.restype = Location
loc = library.collect()
print loc.latitude, loc.longitude
<小时/>
顺便说一句:你提到了 Django;我在这里会小心并发。请注意,您的 C 库可能会从不同的线程调用。
关于python - c 数组到 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589883/