为了加快struct.pack()
的速度,我将以下内容打包为字节:
import cython as c
from cython import nogil, compile, returns, locals, cfunc, pointer, address
int_bytes_buffer = c.declare(c.char[400], [0] * 400)
@locals(i = c.int, num = c.int)
@returns(c.int)
@cfunc
@nogil
@compile
def int_to_bytes(num):
i = 0
while num >0:
int_bytes_buffer[i] = num%256
num//=256
i+=1
return int_bytes_buffer[0]
int_to_bytes(259)
我正在尝试使用以下错误代码将其用于int列表:
@locals(i = c.int, ints_p = pointer(c.int[100]), num = c.int)
@returns(c.int)
@cfunc
@nogil
@compile
def int_to_bytes(num):
i = 0
for num in ints_p:
while num >0:
int_bytes_buffer[i] = num%256
num//=256
i+=1
return int_bytes_buffer[0]
ints = c.declare(c.int[100], [259]*100)
int_to_bytes(address(ints))
这给了我:
for num in ints_p:
^
----------------------------------------------------------
Accessing Python global or builtin not allowed without gil
显然,我不应该使用in
,也不应该在指针上循环。
如何在函数内部遍历list-made-array?
编辑:
我正在尝试将指向整数数组的指针传递给该函数,并使其在没有gil的情况下工作,以便可以对其进行并行化。
该函数的参数应该是ints_p:
@locals(ints_p = pointer(c.int[100]), i = c.int, num = c.int)
@returns(c.int)
@cfunc
@nogil
@compile
def int_to_bytes(ints_p):
i = 0
for num in (*ints_p):
while num >0:
int_bytes_buffer[i] = num%256
num//=256
i+=1
return int_bytes_buffer[0]
ints = c.declare(c.int[100], [259]*100)
int_to_bytes(address(ints))
并且我想在实际的整数上运行并打包(没有gil)
您的代码中有一些错误。