python函数参数类型可以是结构体吗_Python 如何给 c 函数传递结构体参数?有人知道吗...

项目中现在遇到这么一个问题,函数是用 c 写的,调用要用到 python,因为是在 linux 环境,所以是直接调用的动态库 SO 文件,调用方式我已经搞定了,但是不知道怎么用 pyton 给 c 函数传递结构体参数,网上找了一些例子,但没调通,不知道是哪里不对,请教各位了,帖一下简单的代码例子:

//test1.c

# include

# include

struct Student

{

char name[30];

float fScore[3];

};

void Display(struct Student su)

{

printf("-----Information------\n");

printf("Name:%s",su.name);

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

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

printf("English:%.2f",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 调用 c 的代码:

#pycall.py

import ctypes

from ctypes import *

class Student(Structure):

_fields_ = [("param1",c_char_p),

("param2", c_float * 3)

]

su = Student()

su.param1 = b"testsdk"

PARAM = c_float * 3

param2 = PARAM()

param2[0] = 1.1

param2[1] = 1.2

param2[2] = 1.3

su.param2 = param2

if __name__ == '__main__':

ll = ctypes.cdll.LoadLibrary

lib = ll("./libpycall.so")

lib.Display(byref(su))

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

============================================================

我期望的结果是按以下代码执行

//test1_demo.c

# include

# include

//创建一个 Student 结构体

struct Student

{

char name[30];

float fScore[3];

};

struct Student su = {"testsdk",98.5,89.0,93.5};

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("平均分数为:%.2f\n",(su.fScore[0]+su.fScore[1],su.fScore[2])/3);

}

int main ()

{

Display(su);

return 0;

}

输出(这是我想用 python 调用的期望结果)

-----Information------

Name:testsdk

Chinese:98.50

Math:89.00

English:93.50

平均分数为:31.17

[Finished in 0.3s]

但我用 python 调用的时候,传递的结构体识别不了,都是空的,应该是没识别是结构体

-----Information------

Name:

Chinese:0.00

Math:0.00

English:0.00

平均分数为:0.00

----- finish -----

求各位指教,谢谢大家

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值