python中使⽤动态库
⾸先,创建⼀个简单的动态库
编程⽣成dll.so: gcc -fPIC -O2 -shared dll.c -o dll.so
C⽂件:dll.c 如下
#include <stdio.h>
struct param {
int a;
int b;
char c;
float f;
int arr[3];
};
void print0(struct param arg)
{
printf("in print:\n");
printf("a: %d\n", arg.a);
printf("b: %d\n", arg.b);
printf("c: %c\n", arg.c);
printf("f: %f\n", arg.f);
printf("arr: %d %d %d\n", arg.arr[0], arg.arr[1], arg.arr[2]);
}
void print2(struct param *arg)
{
printf("in print2 :\n");
printf("a: %d\n", arg->a);
printf("b: %d\n", arg->b);
printf("c: %c\n", arg->c);
printf("f: %f\n", arg->f);
printf("arr: %d %d %d\n", arg->arr[0], arg->arr[1], arg->arr[2]);
}
void print3(int a)
{
printf("in print3:\n");
printf("a: %d\n", a);
python printf输出格式}
python定义传给动态库的结构体
from ctypes import *
class ss(Structure):
_fields_ = [
("a", c_int),
("b", c_int),
("c", c_char),
("f", c_float),
("arr", c_int*3), //定义数组
]
python 使⽤dll.so实例
#加载动态库
fileName = "/home/primax/Desktop/Work/Test/python/dll.so"
lib = cdll.LoadLibrary(fileName)
#定义变量
param = ss()
#给结构体赋值
param.a = 1
param.b = 2
param.c = 'a'
param.f = 1.2345
param.arr[0] = 0
param.arr[1] = 1
param.arr[2] = 2
lib.print0(param)
lib.print3(2)
#传指针 pointer取指针
lib.print2(pointer(param))
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论