Python implementation on Linux C language function calls

General idea

Built-in Python ctypes library to be called c compiled .so file to implement the function call.
Suppose we need to call the c file called test.c, file there is a function func (x, y) we need.

.C file is compiled into a .so file

gcc -fPIC -shared test.c -o test.so

After running will see that there test.so file generation.

C import file in Python

Open Python in the current directory

import os
from ctypes import *

p = os.getcwd() + '/test.so’ #表示.so文件的绝对路径,如果你没在当前路径打开python则可能需要修改
f = CDLL(p) #读取.so文件并赋给变量f

If there is no error this time, it shows the .so file import is successful, you can call the function script.

call function

# 变量为整数
a = 3
b = 4
f.func(a, b) #该步即运行函数func(x,y)

# 变量为浮点数
c = c_float(5.5)
d = c_float(6.66)
f.func(c, d)

It is more than a simple form to call functions in C.

Complications

Sometimes, we need a script in C, call the other libraries, or also called the same level of C script .h form is called. This situation requires the following steps:

All .c file compiled to .o file

This step is to go according to your needs compiled, but remember to join -fPIC , generate one or more .o files compiled. If you have only one C script (that is, not the same level of C calling other script), of course, only a .o file. Several C script generates several .o files.

All .o files compiled into a .so file

gcc -shared -o main.so *.o -lfftw3

The above command all the .o files compiled into main.so files, last -lfftw3 represent other C library calls the script, I was fftw3 library, you need to add the library name to call your own. After running the file can be generated main.so
available ldd -r main.so view .so file, if does not appear undefined Symbol , the compiler should be correct.

Run the script

If you need to run scripts instead of only one function, the script can be run directly in the main function

import os
from ctypes import *

p = os.getcwd() + '/test.so’
f = CDLL(p)
f.main() #运行C脚本中的main函数

Guess you like

Origin www.cnblogs.com/guiguiguoguo/p/11777056.html