python - c 数组到 python

标签 python c ctypes

我需要使用共享库(.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/

相关文章:

python - 获取要在 Qt 小部件中显示的子进程的标准输出

python - 自定义表情符号和动画表情符号不起作用 [discord.py-rewrite]

python - jinja2 + 重构标记

c - 进程返回 -1 (0xFFFFFFFF)

c - 为什么在 glibc libc-lock.h 中使用三个 *?

python - 如何获取 python ctypes 结构成员的长度以格式化十六进制输出?

python - 将三重指针数组转换为 numpy 数组或列表 python

python - igraph python 导入错误

c++ - 有没有一种方法可以有效地进行小的固定范围乘法?

python ctypes Win32方式窗口标题被截断?