Python calls a shared library Method Instance developed in C language, and a python instance
In the helloworld project, I wrote a simple program for adding two values. After being compiled 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.
Copy codeThe 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;
Copy codeThe 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)
Copy codeThe Code is as follows:
>>> Import ctypes
Open the dynamic library of the current directory
Copy codeThe Code is as follows:
>>> Lib = ctypes. cdll. LoadLibrary ("./libhelloworld. so.0.0.0 ")
Call interfaces in a dynamic library
Copy codeThe Code is as follows:
>>> Lib. add (5, 7)
12
The function for adding two parameters is as follows:
Copy codeThe Code is 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;
}
Compile the dynamic library command line:
Copy codeThe Code is as follows:
Gcc-shared-fPIC-DPIC helloworld. c-o libhelloworld. so.0.0.0