Python calls a shared library method instance developed by C language _python

Source: Internet
Author: User

In the HelloWorld project, a simple two-sum program was written, how to use Python to invoke it after compiling it into a shared library?

Use the LL command to list the shared libraries under the current directory, where the shared library name is libhelloworld.so.0.0.0

Copy Code code as follows:

ufo@ufo:~/helloworld/.libs$ LL
Total Dosage 32
Drwxr-xr-x 2 UFO UFO 4096 January 29 14:54./
Drwxr-xr-x 6 UFO UFO 4096 January 29 16:08. /
-rw-r--r--1 UFO UFO 3816 January 14:54 HELLOWORLD.O
-rw-r--r--1 UFO UFO 3956 January 14:54 libhelloworld.a
lrwxrwxrwx 1 UFO UFO 19 January 14:54 libhelloworld.la->. /libhelloworld.la
-rw-r--r--1 UFO UFO 983 January 14:54 Libhelloworld.lai
lrwxrwxrwx 1 UFO UFO 22 January 14:54 libhelloworld.so-> libhelloworld.so.0.0.0*
lrwxrwxrwx 1 UFO UFO 22 January 14:54 libhelloworld.so.0-> libhelloworld.so.0.0.0*
-rwxr-xr-x 1 UFO UFO 9038 January 14:54 libhelloworld.so.0.0.0*

Call into Python's command line mode for the two numeric addition programs implemented in C language;
Copy Code code as follows:

ufo@ufo:~/helloworld/.libs$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:56)
[GCC 4.7.3] on linux2
Type ' help ', ' copyright ', ' credits ' or ' license ' for the more information.

Load the cTYPES class (this class is the method that invokes the C language dynamic library)
Copy Code code as follows:

>>> Import cTYPES

Open the dynamic library for the current directory
Copy Code code as follows:

>>> lib=ctypes.cdll.loadlibrary ("./libhelloworld.so.0.0.0")

Calling interfaces in a dynamic library
Copy Code code as follows:

>>> Lib.add (5,7)
12

The function of the addition of two parameters is as follows:
Copy Code code as follows:

ufo@ufo:~/helloworld$ Cat HELLOWORLD.C
#include <stdio.h>
#include <stdlib.h>

int add (int a, int b)
{
int C = a + B;
return C;
}


To compile the command line for a dynamic library:
Copy Code code as follows:

Gcc-shared-fpic-dpic Helloworld.c-o libhelloworld.so.0.0.0

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.