Python binding using ctype
Assuming there is already a shared c library, we can load this in python using following statement.
shared_lib = "path to shared library"
c_lib = ctype.CDDL(shared_lib)
c_lib
has all the function present in shared library as attributes.
Let’s see there is a function mul
which takes an integer and a float and returns the product of it as float.
By default, ctype
marshalling process passes all the data as integer so we need to explicitly tell ctype
to use float
.
c_lib.mul(2, ctype.c_float(2.3)) ## FAILS
The above statement fails. The reason being the return type is float
and marshalling is not happening correctly from ctype
end. Again we need to specify it.
c_lib.mul.restype = ctype.c_float
Now, it will work.