我有一个20字节的字符串,我想将其转换为ctypes.c_ubyte数组以进行位字段操作.
import ctypes
str_bytes = '01234567890123456789'
byte_arr = bytearray(str_bytes)
raw_bytes = (ctypes.c_ubyte*20)(*(byte_arr))
有没有办法避免为了演员而从str到bytearray的深拷贝?
或者,是否可以在没有深层复制的情况下将字符串转换为bytearray? (使用memoryview等技术?)
我使用的是Python 2.7.
表现结果:
使用eryksun和Brian Larsen的建议,这里是使用Ubuntu 12.04和Python 2.7的vbox VM下的基准测试.
> method1使用我原来的帖子
> method2使用ctype from_buffer_copy
> method3使用ctype cast / POINTER
> method4使用numpy
结果:
> method1需要3.87秒
> method2需要0.42秒
> method3需要1.44秒
> method4需要8.79秒
码:
import ctypes
import time
import numpy
str_bytes = '01234567890123456789'
def method1():
result = ''</