Home >Backend Development >Python Tutorial >Detailed explanation of how Python calls C language functions

Detailed explanation of how Python calls C language functions

黄舟
黄舟Original
2017-10-03 05:43:402664browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn