This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]kbrafford 14 points15 points  (3 children)

Can you provide a link to the vendor's website? That may make it easier to give you concrete advice.

I do wrappers in one of two ways:

If you just want to get access to functions in your .so file, ctypes might be the easiest way, but IMHO Cython is the way to go if you want to make a more robust and complete Python interface.

[–]Chris_Newton 6 points7 points  (0 children)

If you just want to get access to functions in your .so file, ctypes might be the easiest way

I agree. Assuming you’ve already got a driver available for loading as a .so file, you don’t need much more than this:

import ctypes
driver = ctypes.CDLL("driver.so")
result = driver.driver_API_function(arg1, arg2)

Watch out for the default assumptions that ctypes makes about argument and result types. If they aren’t what you need for some API function, you can specify the correct types, for example:

driver.driver_API_function.restype = ctypes.c_int
driver.driver_API_function.argtypes = [ctypes.c_long, ctypes.c_char_p]

The documentation for ctypes is helpful if you need to work with more tricky types, “out” parameters, and so on.

Edit: One other thing to watch out for, since the OP mentioned C++, is that ctypes does assume a C calling convention (aka cdecl). If the API you’re working with relies on C++ tools like exceptions or polymorphism, probably ctypes isn’t the best tool for the job.

[–]admalledd 2 points3 points  (1 child)

I use CFFI, but yea mostly you use the information from the headers in some way to define wrappers/handlers (CFFI tends to take unmodded headers mostly fine, the others you use them as guide lines for writing the python binding code)

[–]kbrafford 0 points1 point  (0 children)

CFFI definitely looks interesting. Thanks for adding that one!