Python calls an instance of a Shared library method developed in C

  • 2020-04-02 14:40:45
  • OfStack

In the helloworld project, you wrote a simple program that adds two values, compiled it into a Shared library, and how do you call it in python?

Use the ll command to list the Shared libraries in the current directory under the name libhelloworld.so.0.0.0


ufo@ufo:~/helloworld/.libs$ ll
The total amount 32
drwxr-xr-x 2 ufo ufo 4096  1 month 29 14:54 ./
drwxr-xr-x 6 ufo ufo 4096  1 month 29 16:08 ../
-rw-r--r-- 1 ufo ufo 3816  1 month 29 14:54 helloworld.o
-rw-r--r-- 1 ufo ufo 3956  1 month 29 14:54 libhelloworld.a
lrwxrwxrwx 1 ufo ufo   19  1 month 29 14:54 libhelloworld.la -> ../libhelloworld.la
-rw-r--r-- 1 ufo ufo  983  1 month 29 14:54 libhelloworld.lai
lrwxrwxrwx 1 ufo ufo   22  1 month 29 14:54 libhelloworld.so -> libhelloworld.so.0.0.0*
lrwxrwxrwx 1 ufo ufo   22  1 month 29 14:54 libhelloworld.so.0 -> libhelloworld.so.0.0.0*
-rwxr-xr-x 1 ufo ufo 9038  1 month 29 14:54 libhelloworld.so.0.0.0*

Enter the command line mode of python for C language implementation of the program to add two values of the call;

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 (which is the method that calls the C language dynamic library)

>>> import ctypes

Open the dynamic library for the current directory

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

Invoke the interface in the dynamic library

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

The function of adding two parameters 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 command line for the dynamic library:

gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0


Related articles: