The following editor will bring you an example of how python calls c language functions. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look
Although python is omnipotent, some special functions require C language to complete. In this way, you need to use python to call c code
Specific process:
C writes relevant functions and compiles them into a library
Then load these libraries in python and specify the calling function.
These functions can be char, int, float, and can also return pointers.
The following example:
Call the c function through python and return "hello,world string"
Create a new c language File hello.c
touch hello.c
#include <stdio.h> char *get_str() { return "hello,world" }
Compile into 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_p str = dll.get_str() print(string_at(str, 11))
Execute python script
[feng@arch python_c]$ python test.py hello,world
The above is the detailed content of Detailed explanation of how Python calls C language functions. For more information, please follow other related articles on the PHP Chinese website!