0

共有ライブラリ (.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>;
}

私は初心者なので、そのような種類のデータを配信する方法はありますか?

4

1 に答える 1

1

1 つのオプションは、ポインター パラメーターを介して値を返すことです。

// 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 ライブラリは異なるスレッドから呼び出される可能性があることに注意してください。

于 2013-01-29T18:48:11.283 に答える