2016-05-08 5 views
0

Python関数があります。これはCPython 2.5.3で動作しますが、Jython 2.5.3ではクラッシュします。 Apache Pigのユーザ定義関数の一部です.Jython 2.5.3を使用していますので変更できません。Jython 2.5.3でのキャスト

入力は1バイトの配列ですが、実際には符号なしバイトなので、それをキャストする必要があります。

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にimplemetedされていないと思います。その問題の回避策はありますか?ここで

おかげで、 ステファン

+0

このコードは可能性が 'struct.unpack'と' struct.pack'、参照[構造体モジュール(https://docs.python.org/2/library/struct.html)を使用して再実装することができます –

答えて

0

は非常に醜いですが、追加の依存性をせずに動作します私のソリューションです。 使用済みの符号付きバイト(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) 
関連する問題