0

I need to handle a big array of data from C program to python instance (Django) using shared library (.so). Is it possible to return them through ctypes ?

For example:

import ctypes
a = ctypes.CDLL('foo.so')
b = a.collect()
latitude  = b.latitude
longitude = b.longitude

and a C:

main()
{
    /* steps to get the data */
    return <kind of struct or smth else>;
}

I am the newbie so is there a ways of delivery of such kind of data ?

1 Answer 1

1

One option is to return the values via pointer parameters:

// c 
void collect(int* outLatitude, int* outLongitude) {
    *outLatitude = 10;
    *outLongitude = 20;
}

and

# python
x = ctypes.c_int()
y = ctypes.c_int()
library.collect(ctypes.byref(x), ctypes.byref(y))
print x.value, y.value

If you need more than that, you could return a structure:

// c
typedef struct  {
    int latitude, longitude;
} Location;

Location collect();

and

# 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

BTW: You have mentioned Django; I'd be careful with concurrency here. Note that your C library may be called from different threads.

Sign up to request clarification or add additional context in comments.

5 Comments

BTW other solutions: a) See projects like ctypesgen to read headers and write these Python definitions for you. b) Use boost::python or SWIG to compile the C/C++ code into a real Python module. You can also read my article: 5 ways to use Python with native code.
there are no problems with c_int. Now i can't figure out how to use c_char_p and pass strings to python. Can you give a sample ?
See Fundamental data types in the docs, I can't describe that better. (For simple read-only passing, you can just pass a Python string to the function, assuming it has argtypes set correctly - ctypes will autoconvert)
i meant a pointer to string from C to python and get it as x.value for example
Oh, in this way. Set the function's restype to c_char_p and it should return Python strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.