python调用C语言库

1. 在linux下通过gcc生成so库

复制代码
//请保存为 foo.c
#include<stdio.h>
#define uint8_t   unsigned char
#define uint16_t  unsigned short
                                                     
                                                     
typedef 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文件

python 复制代码
#请保存为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)

 

运行效果:

相关推荐
micro_xx几秒前
借助Matlab有限元工具pde进行静态结构有限元分析
开发语言·matlab
代码无bug抓狂人2 分钟前
C语言之可分解的正整数(蓝桥杯省B)
c语言·开发语言·算法
Cher ~3 分钟前
常见C++编译器套件
开发语言·c++
上海合宙LuatOS5 分钟前
LuatOS ——Modbus RTU 通信模式
java·linux·服务器·开发语言·网络·嵌入式硬件·物联网
xyq202412 分钟前
《jEasyUI 启用行内编辑》
开发语言
野生技术架构师12 分钟前
Java 21虚拟线程 vs Kotlin协程:高并发编程模型的终极对决与选型思考
java·开发语言·kotlin
言之。16 分钟前
Kotlin快速入门
android·开发语言·kotlin
Vivienne_ChenW20 分钟前
DDD领域模型在项目中的实战
java·开发语言·后端·设计模式
牙牙要健康22 分钟前
【open3d】Windows 下编译 Open3D C++ 源码完整教程
开发语言·c++·windows
不染尘.27 分钟前
二叉树相关题目
开发语言·数据结构·c++·算法