2022年 11月 5日

使用 Python 调用 .so 文件?

jiaming@ubuntu:~/project$ tree .
.
├── hello.c
├── hello.py
└── mylib.so

0 directories, 3 files
jiaming@ubuntu:~/project$ cat hello.c
#include <stdio.h>
# 字符指针
void display(char* string)
{
	printf("%s\n", string);
}
# 浮点传参,以及返回浮点数
float multi(float a, float b)
{
	return a*b;
}
# 传入整型指针
void modify_array(int array[], int num)
{
    int i = 0, sum = 0;
   	for(i=0; i<num; i++)
        	array[i] *= 10;
}
jiaming@ubuntu:~/project$ cat hello.py 
import ctypes
import numpy as np
from ctypes import cdll
so = cdll.LoadLibrary('./mylib.so')

so.display("dslab")

# 规定函数参数类型以及函数返回值类型
so.multi.argtypes = [ctypes.c_float, ctypes.c_float]
so.multi.restype = ctypes.c_float
a = 2.5
b = 3.0
print so.multi(a, b)

# 将列表转换为数组传入并返回修改后的列表
pyarray = [1,2,3,4,5,6,7,8]
carray = (ctypes.c_int*len(pyarray))(*pyarray)
so.modify_array(carray, len(pyarray))
print np.array(carray)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46