zoukankan      html  css  js  c++  java
  • python调用c/c++时传递结构体参数

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

    //test1.c

    # include <stdio.h> # include <stdlib.h> //创建一个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 * 3 fScore = PARAM() fScore[0] = 55.1 fScore[1] = 33.2 fScore[2] = 51.3 su.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-sdk
    Chinese:55.10
    Math:33.20
    English:51.30
    总分数为:139.600006
    平均分数为:46.53
    ----- finish -----
  • 相关阅读:
    vue axios创建实例
    vue axios全局配置
    vue axios并发请求
    vue axios HTTP 库
    vuex actions异步操作
    vuex getters
    Go并发控制--Channel篇
    UVA10228 A Star not a Tree?
    P1395 会议
    P1337 [JSOI2004]平衡点 / 吊打XXX
  • 原文地址:https://www.cnblogs.com/pyse/p/8590829.html
Copyright © 2011-2022 走看看