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)

 

运行效果:

相关推荐
RuoZoe8 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_11 天前
C语言内存函数
c语言·后端
郑州光合科技余经理13 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12313 天前
matlab画图工具
开发语言·matlab
dustcell.13 天前
haproxy七层代理
java·开发语言·前端
norlan_jame13 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone13 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549613 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy878747513 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月13 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js