【问题标题】:Casting in Jython 2.5.3在 Jython 2.5.3 中进行铸造
【发布时间】:2016-05-08 14:54:56
【问题描述】:

有一个 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'

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

谢谢, 史蒂芬

【问题讨论】:

  • 可以使用struct.unpack 和struct.pack 重新实现该代码,请参阅struct module

标签: casting apache-pig jython ctypes


【解决方案1】:

这是我的解决方案,它非常难看,但无需额外的依赖即可工作。 它使用已使用和带符号字节的位表示 (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)

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多