1. 在linux下通过gcc生成so库
//请保存为 foo.c
#include<stdio.h>
#define uint8_t unsigned char
#define uint16_t unsigned shorttypedef struct TagMyStruct
{char name[10];uint8_t age;int score;
} MyStruct,*MyStructPointer;MyStructPointer foo_get_data_pointer() // 返回结构体指针
{MyStructPointer pt = (MyStructPointer)malloc(sizeof(MyStructPointer));strcpy(pt->name, "Joe");pt->age = 19;pt->score = 95;return pt;
}MyStruct foo_get_data_self() // 返回结构体
{return (MyStruct){"Jack",15,100};
}void foo_func()
{printf("Hello_world,foo_func()\n");return;
}int foo_add(int a,int b)
{return a+b;
}
gcc -fPIC -c foo.c -o foo.o
gcc -shared -o libfoo.so foo.o
2.通过如上指令生成libfoo.so库文件,用python运行如下py文件
#请保存为test.py
from ctypes import *
# 加载动态链接库
lib = cdll.LoadLibrary('./libfoo.so')
# 调用 C 函数
result = 0
result = lib.foo_func()
print("foo_func,ret=",result)result = lib.foo_add(100,200)
print("foo_add,ret=",result)class MyStruct(Structure):_fields_ = [('name', c_char*10),('age', c_ubyte),('score', c_int), ]lib.foo_get_data_self.restype = MyStruct #指定函数返回值结构体本身
dat = lib.foo_get_data_self()
print("=====get struct self from .so function=======")
print("name=",dat.name)
print("age=",dat.age)
print("score=",dat.score)lib.foo_get_data_pointer.restype = POINTER(MyStruct) #指定函数返回值结构体指针
dat = lib.foo_get_data_pointer()
print("=====get struct point from .so function=======")
print("name=",dat.contents.name)
print("age=",dat.contents.age)
print("score=",dat.contents.score)
运行效果: