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

Detailed explanation of how Python calls C language functions

黄舟
Release: 2017-10-03 05:43:40
Original
2606 people have browsed it

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
Copy after login


#include <stdio.h>

char *get_str()
{
 return "hello,world"
}
Copy after login

Compile into library


gcc -o hello.so --share -fPIC hello.c
Copy after login

New python Script


touch test.py
Copy after login


from ctypes import *

dll = CDLL("./hello.so")
dll.get_str.restype = c_char_p
str = dll.get_str()
print(string_at(str, 11))
Copy after login

Execute python script


[feng@arch python_c]$ python test.py 
hello,world
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template