在 Jython 2.5.3 中铸造

Casting in Jython 2.5.3

有一个 Python 函数,它在 CPython 2.5.3 中运行,但在 Jython 2.5.3 中崩溃。 它是 Apache Pig 中用户定义函数的一部分,它使用 Jython 2.5.3,所以我无法更改它。

输入是一个单字节数组,但实际上是无符号字节,所以我需要转换它。

from StringIO import StringIO
import array
import ctypes

assert isinstance(input, array.array), 'unexpected input parameter'
assert input.typecode == 'b', 'unexpected input type'

buffer = StringIO()
for byte in input:
    s_byte = ctypes.c_byte(byte)
    s_byte_p = ctypes.pointer(s_byte)
    u_byte = ctypes.cast(s_byte_p, ctypes.POINTER(ctypes.c_ubyte)).contents.value
    buffer.write(chr(u_byte))
buffer.seek(0)
output = buffer.getvalue()

assert isinstance(output, str)

错误是:

s_byte = ctypes.cast(u_byte_p, ctypes.POINTER(ctypes.c_byte)).contents.value
AttributeError: 'module' object has no attribute 'cast'

我猜 Jython 2.5.3 中没有实现 ctypes.cast 函数。这个问题有解决方法吗?

谢谢, 斯蒂芬

这是我的解决方案,虽然很丑陋,但无需额外的依赖项即可工作。 它使用无符号和有符号字节的位表示(https://de.wikipedia.org/wiki/Zweierkomplement)。

import array

assert isinstance(input, array.array), 'unexpected input parameter'
assert input.typecode == 'b', 'unexpected input type'

output = array.array('b', [])

for byte in input:

    if byte > 127:
        byte = byte & 127
        byte = -128 + byte

    output.append(byte)