SoFunction
Updated on 2024-11-17

Example of Python calling a C-developed shared library method

After writing a simple program to add two values in a helloworld project and compiling it as a shared library, how do I call it using python?

Use the ll command to list the shared libraries in the current directory, where the shared library is named .0.0.0

Copy Code The code is as follows.

ufo@ufo:~/helloworld/.libs$ ll
Total usage 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 29 14:54
-rw-r--r-- 1 ufo ufo 3956 January 29 14:54
lrwxrwxrwx 1 ufo ufo 19 January 29 14:54 -> ... /
-rw-r--r-- 1 ufo ufo 983 January 29 14:54
lrwxrwxrwx 1 ufo ufo 22 January 29 14:54 -> .0.0.0*
lrwxrwxrwx 1 ufo ufo 22 January 29 14:54 .0 -> .0.0.0*
-rwxr-xr-x 1 ufo ufo 9038 January 29 14:54 .0.0.0*

Enter python's command line mode to make a call to a C implementation of a program that adds two values;
Copy Code The code is 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 more information.

Load the ctypes class (this class is the method to call the C dynamic library)
Copy Code The code is as follows.

>>> import ctypes

Open the dynamic library in the current directory
Copy Code The code is as follows.

>>> lib=("./.0.0.0")

Calling interfaces in dynamic libraries
Copy Code The code is as follows.

>>> (5,7)
12

The function for adding two arguments is as follows.
Copy Code The code is as follows.

ufo@ufo:~/helloworld$ cat
#include <>
#include <>

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


Command line for compiling dynamic libraries:
Copy Code The code is as follows.

gcc -shared -fPIC -DPIC -o .0.0.0