This article mainly introduces the example of using Python to call the shared library method developed by C language. This article also provides a simple example of calling C language and Python. if you need a shared library, refer to the helloworld project, I have compiled a simple program for adding two numeric values. after compiling it into a shared library, how can I use python to call it?
Use the ll command to list the shared libraries in the current directory. the shared libraries are named libhelloworld. so.0.0.0.
The code is as follows:
Ufo @ ufo :~ /Helloworld/. libs $ ll
Total usage 32
Drwxr-xr-x 2 ufo 4096 January 29 14:54 ./
Drwxr-xr-x 6 ufo 4096 January 29 16:08 ../
-Rw-r -- 1 ufo 3816 January 29 14:54 helloworld. o
-Rw-r -- 1 ufo 3956 14:54 libhelloworld.
Lrwxrwxrwx 1 ufo 19 January 29 14:54 libhelloworld. la->.../libhelloworld. la
-Rw-r -- 1 ufo 983 14:54 libhelloworld. lai
Lrwxrwxrwx 1 ufo 22 January 29 14:54 libhelloworld. so-> libhelloworld. so.0.0.0 *
Lrwxrwxrwx 1 ufo 22 January 29 14:54 libhelloworld. so.0-> libhelloworld. so.0.0.0 *
-Rwxr-xr-x 1 ufo 9038 14:54 libhelloworld. so.0.0.0 *
Go to the command line mode of python to call two programs whose values are added in C language;
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 language dynamic Library)
The code is as follows:
>>> Import ctypes
Open the dynamic library of the current directory
The code is as follows:
>>> Lib = ctypes. cdll. LoadLibrary ("./libhelloworld. so.0.0.0 ")
Call interfaces in a dynamic library
The code is as follows:
>>> Lib. add (5, 7)
12
The function for adding two parameters is as follows:
The code is as follows:
Ufo @ ufo :~ /Helloworld $ cat helloworld. c
# Include
# Include
Int add (int a, int B)
{
Int c = a + B;
Return c;
}
Compile the dynamic library command line:
The code is as follows:
Gcc-shared-fPIC-DPIC helloworld. c-o libhelloworld. so.0.0.0