Launching compiled code with Ctypes

We will now give a brief overview of the Ctypes module from the Python Standard Library. Ctypes is used for calling functions from the Linux .so (shared object) or Windows. DLL (Dynamically Linked Library) pre-compiled binaries. This will allow us to break out of the world of pure Python and interface with libraries and code that have been written in compiled languages, notably C and C++—it just so happens that Nvidia only provides such pre-compiled binaries for interfacing with our CUDA device, so if we want to sidestep PyCUDA, we will have to use Ctypes.

Let's start with a very basic example: we will show you how to call printf directly from Ctypes. Open up an instance of IPython and type import ctypes. We are now going to look at how to call the standard printf function from Ctypes. First, we will have to import the appropriate library: in Linux, load the LibC library by typing libc = ctypes.CDLL('libc.so.6') (in Windows, replace 'libc.so.6' with 'msvcrt.dll'). We can now directly call printf from the IPython prompt by typing libc.printf("Hello from ctypes! "). Try it for yourself!

Now let's try something else: type libc.printf("Pi is approximately %f. ", 3.14) from IPython; you should get an error. This is because the 3.14 was not appropriately typecast from a Python float variable to a C double variablewe can do this with Ctypes like so:

libc.printf("Pi is approximately %f.
", ctypes.c_double(3.14)) 

The output should be as expected. As in the case of launching a CUDA kernel from PyCUDA, we have to be equally careful to typecast inputs into functions with Ctypes.

Always be sure to appropriately typecast inputs into any function that you call with Ctypes from Python to the appropriate C datatypes (in Ctypes, these are preceded by c_: c_float, c_double, c_char, c_int, and so on).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.143