The following small series for everyone to bring a Python call C language functions of the example explained. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
Although Python is omnipotent, it requires C language for certain special functions. In this way, you need to use Python to invoke C's code.
Specific process:
C Write related functions, compile into library
These libraries are then loaded in Python, specifying the calling function.
These functions can be char, int, float, and can also return pointers.
The following example:
Call C function via Python, return "Hello,world string"
New C language File hello.c
Touch hello.c
#include <stdio.h>char *get_str () {return "Hello,world"}
Compiling into a library
Gcc-o hello.so--share-fpic hello.c
New Python Script
Touch test.py
From ctypes Import *dll = Cdll ("./hello.so") Dll.get_str.restype = C_char_pstr = Dll.get_str () print (String_at (str, 11))
Execute Python Script
[Feng@arch python_c]$ python test.py hello,world