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)

 

运行效果:

相关推荐
Navigator_Z1 小时前
LeetCode //C - 1208. Get Equal Substrings Within Budget
c语言·算法·leetcode
xx~t2 小时前
嵌入式——进程与线程1
linux·c语言·学习·嵌入式·进程与线程
m0_547486662 小时前
《JavaScript核心原理 》全套PPT课件2026
开发语言·javascript·ecmascript
老当益壮梁奶奶2 小时前
Linux软件编程学习笔记(七):线程分离与线程间通信详解
linux·c语言·c++·笔记·学习
MC皮蛋侠客3 小时前
Tauri 2.x 系列(五):调用系统 API——官方插件、Rust crate 与原生能力
开发语言·后端·rust
布莱克6053 小时前
软中断和硬中断的区别
开发语言·操作系统
whcyhhh4 小时前
头歌实践教学平台:数据科学与大数据技术导论(十二)
大数据·开发语言·python·数据清洗
lzhdim4 小时前
13、JavaScript事件循环机制 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
zbyyd5 小时前
Linux 多线程:互斥锁 &amp; 信号量
linux·c语言·开发语言·网络
wuyk5555 小时前
从零吃透Modbus通信|第3章:STM32 Modbus RTU主机
服务器·开发语言·网络·数据结构·stm32·单片机·嵌入式硬件