Python中的C指针算法

2024-04-26 23:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个简单的C程序转换成Python,但由于我对C一无所知,对Python也略知一二,这对我来说很困难。。在

我被C指针卡住了。在

有一个函数接受无符号长整型指针,并将其值添加到while循环中的某些变量:

uint32_t somename(const uint32_t *z) {
    while(....) {
        a += z[0]
        b += z[1]
        c += z[2]
        z += 3
    }
}

有人能告诉我如何用python完成同样的事情吗? (我完全不明白的部分是“z+=3”)

我知道python中没有指针。(至少不象C)但问题是我不知道C指针到底是做什么的,因此不能在python中实现这一点。在


Tags: 函数事情指针whileconstuint32somename符号长
3条回答

z += 3的意思是将指针下移3个元素。假设您有一个指向C中名为lst的数组的指针,其中包含[1, 2, 3, 4]。指针lst指向第一个元素,这样*lst等同于lst[0]。此外,*(lst+1)相当于lst[1]。在

假设z作为一个列表传递(在相应的python代码中)。z += 3可以转换为del z[:3],它将元素3移到0。 但是在python中,在执行此操作之前需要复制数组,因为使用del语句,数组会被修改。在

在C中,您可以通过负索引访问指向索引之前的元素。这可以通过嵌套在类中的“不可见”偏移量来实现。访问列表时,总是将此偏移量添加到索引中。 下面的类演示该行为。在

class pointer_like:
    def __init__(self, lst):
        self.lst = lst; self.offset = 0

    # self[index]
    def __getitem__(self, index):
        return self.lst[self.offset + index]

    # self += offset
    def __iadd__(self, offset):
        self.offset += offset

    # other member functions...

# as your example above
def somename(z):
    z = pointer_like(z)
    while (....):
        a += z[0]
        b += z[1]
        c += z[2]
        z += 3

>>> # other example
>>> z = pointer_like([0, 1, 2, 3, 4, 5])
>>> z[0]
0
>>> z += 3
>>> z[0]
3
>>>
>>> # with normal python lists, this would mean third last element
>>> z[-3]
0
>>> z += -5
>>> z[2]
0
>>>
>>> # this is special, because z.offset is negative (-2),
>>> # when a list item is accessed through a negative index,
>>> # it is counted from the end of the array in python.
>>> # In this case, it is -2, so the second last is accessed
>>> # In C this would cause undefined behavor, on most
>>> # platforms this causes an access violation
>>> z[0]
4

注意pyhon还有一个列表的+=运算符,但这允许在末尾附加另一个列表。在

Python中类似的代码片段可能是:

def somename(z):
    i = 0
    while (....):
        a += z[i]
        b += z[i+1]
        c += z[i+2]
        i += 3

在C中,z的工作方式有点像数组索引,只是它从数组开头的任何地址开始,而不是从0开始。Python中没有类似的概念,因此需要显式地使用列表索引。在

(....)中的任何内容也需要修改。我把这个留给你练习,因为问题中没有具体说明。在

相关问题 更多 >