像在C中定义的那样在Python中定义函数 [英] Define function in Python as it defined in C

查看:158
本文介绍了像在C中定义的那样在Python中定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中有一个函数,该函数从给定的缓冲区中逐字节读取并返回数学公式的结果。

我需要在Python中编写相同的函数

I have function in C that reads byte by byte from a given buffer and returns the result of a mathematical formula.
I need to write the same function in Python

C中的缓冲区是 struct ,在python中我使用了 ctypes结构类

我在c中的原型是 int calc_formula(char * buff,int len)

所以在c中调用该函数很容易,但是我如何在Python中定义该函数呢?

The buffer in C is struct and in python i used ctypes Structure class
my prototype in c is int calc_formula(char *buff,int len)
so calling the function in c is staright forward but how i define such function in Python?

我尝试定义以下内容并有一些疑问

I try to define the following and have some questions

def calc_formula(buff,len):
    some code




  1. 在CI中用指针指向strcut的第一个字符。如何在Python中完成?是 buff 作为指针传递的?我的缓冲区很大,如果无法完成,我将使用全局变量(不建议使用)。

  2. 我需要逐字节读取缓冲区,因此在c中我只是增加缓冲区指针。用python做什么?我了解了有关 ctypes联合类的信息,该类可以在 Structure 上定义,并逐字节遍历。您有更好的解决方案吗?

  1. In C I called the function with pointer to the strcut first char. How do I do it in Python? is buff passed as pointer? My buffer is very large and if it can't be done, I will use global variable (which is less preferred).
  2. I need to read the buffer byte by byte, so in c I simply increment the buffer pointer. What's the way to do it in python? I read about ctypes union class that I can define over the Structure and go over it byte by byte. Do you have a better solution?

更新

我尝试过 brame 解决方案:

def calc_formula(buff, len):
    sum = 0     
    for curChar in buff: 
        numericByteValue = ord(curChar) 
        sum += numericByteValue     
    return sum 

with当我尝试使用calc_formula(input_buff,len)编写其代码时,得到以下内容:

* error:TypeError:'t_input_buff 对象不可迭代*-input_buff是t_input_buff的实例,它是Class(Structure)。可能是什么问题?
(尝试执行for命令时会给我错误)

with When i try its code with calc_formula(input_buff,len) , i get the following:
"*error:TypeError: 't_input_buff' object is not iterable*" - input_buff is instance of t_input_buff that is Class(Structure) . what can be the problem? (it give me the error when it try to do the for command)

推荐答案

UPDATE
i使用 ctypes联合类

这个问题

这篇关于像在C中定义的那样在Python中定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆