I found out how to call and use a C language library in Python, so make a note of it.
Compile environment: gcc included in Xcode 10.2. Python:3.7.2
Create a library (libmyadd.so) to call from Python. The contents of the library consist of integer type add functions.
math.c
int add(int a, int b){ return (a + b); }
To create a shared library, run the following command.
gcc -shared -fPIC -o libmyadd.so math.c
This will create libmyadd.so.
The python code for calling this from Python is as follows. It is assumed that the location of the library is the same directory as the source code.
main.py
import ctypes as ct
libc = ct.cdll.LoadLibrary("./libmyadd.so")
if (__name__ == "__main__"):
print(libc.add(1, 2))
As an aside, make a note when calling from C language. It is assumed that the location of the library is the same directory as the source code.
main.c
#include <stdio.h>
int add(int a, int b);
int main(void)
{
printf("%d¥n", add(1, 2));
return 0;
}
Compile this as follows.
gcc -L./ -lmyadd -o main main.c
To do this, do the following:
LD_LIBRARY_PATH=./myadd ./main
This time, I used a package called ctypes of Python to call a shared library of C language that I made from Python. There is still a vague understanding, so I would like to investigate and update the article next time.
The created file is posted on GitHub.
How to create and dynamically link shared libraries on Linux: smart space Python Document 3.7
Recommended Posts