您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页python调用cc++时传递结构体参数

python调用cc++时传递结构体参数

来源:尚车旅游网
python调⽤cc++时传递结构体参数

背景:使⽤python调⽤linux的动态库SO⽂件,并调⽤⾥边的c函数,向⾥边传递结构体参数。直接上代码

//test1.c

# include # include //创建⼀个Student结构体 struct Student{

char name[30]; float fScore[3];};

void Display(struct Student su){

printf(\"-----Information------\\n\"); printf(\"Name:%s\\n\",su.name);

printf(\"Chinese:%.2f\\n\",su.fScore[0]); printf(\"Math:%.2f\\n\",su.fScore[1]); printf(\"English:%.2f\\n\",su.fScore[2]);

printf(\"总分数为:%f\\n\", su.fScore[0]+su.fScore[1]+su.fScore[2]);

printf(\"平均分数为:%.2f\\n\",((su.fScore[0]+su.fScore[1]+su.fScore[2]))/3);}

⽣成libpycall.so⽂件:

gcc -o libpycall.so -shared -fPIC test1.c

python调⽤,给Display传递结构体参数:

#pycall.py

import ctypes

from ctypes import *

class Student(Structure):

_fields_ = [(\"name\",c_char * 30), (\"fScore\", c_float * 3) ]

su = Student()

su.name = b\"test-sdk\"PARAM = c_float * 3fScore = PARAM()fScore[0] = 55.1fScore[1] = 33.2fScore[2] = 51.3su.fScore = fScore

if __name__ == '__main__':

ll = ctypes.cdll.LoadLibrary lib = ll(\"./libpycall.so\")

# lib.Display.restype = c_float

lib.Display.argtypes = [Student] #这⼀⾏很重要 lib.Display(su)

print('----- finish -----')

输出Display函数调⽤结果:

-----Information------Name:test-sdkChinese:55.10Math:33.20English:51.30

总分数为:139.600006平均分数为:46.53----- finish -----

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sceh.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务