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)

 

运行效果:

相关推荐
寻星探路21 分钟前
【算法专题】滑动窗口:从“无重复字符”到“字母异位词”的深度剖析
java·开发语言·c++·人工智能·python·算法·ai
程序员小白条21 分钟前
面试 Java 基础八股文十问十答第八期
java·开发语言·数据库·spring·面试·职场和发展·毕设
Dxy123931021622 分钟前
python连接minio报错:‘SSL routines‘, ‘ssl3_get_record‘, ‘wrong version number‘
开发语言·python·ssl
大王小生26 分钟前
C# CancellationToken
开发语言·c#·token·cancellation
listhi52027 分钟前
基于C#实现屏幕放大镜功能
开发语言·c#
我叫袁小陌1 小时前
C++多线程全面详解
开发语言·c++
lihongli0001 小时前
【工程实战】Win11 + Ubuntu20.04 + Ubuntu24.04 三系统长期稳定安装方案(含避坑指南)
开发语言
黄宝康1 小时前
sublimetext 运行python程序
开发语言·python
m0_748250032 小时前
C++ 官方文档与标准
开发语言·c++
zh_xuan2 小时前
kotlin 类继承的语法2
开发语言·kotlin