How Python invokes the use of C-language functions

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.