2017-03-01 11 views
2

私はPythonにはかなり新しいです。私がしたいのはバイナリファイルからいくつかのCのような構造体を読むことです。構造体は、それらを作成し、Cプログラムでは、次のように定義される。ナンシーな複雑なデータ構造

struct B{ 
    uint16 y; 
    uint8 c[SIZE2]; 
} 

struct A{ 
    uint32 x; 
    struct B b[SIZE1]; 
} 

私はnumpyのパッケージ機能fromFileを使用して、すべてのA-構造体を読み取ることができるようにしたいと思いますが、私は呼び出す方法見当がつかない適切なdtypeメソッド:

record = numpy.dtype([ 
    ("field1", numpy.uint8), 
    ("field2", numpy.uint16), 
    ("field3", numpy.uint32) 
]) 

このような複雑なデータ構造です。

私はそれを書いてもらえますか?前もって感謝します!

+0

[こちら](https://docs.scipy.org/doc/numpy-1.10.1/user/basics.rec.html)を見ましたか?私はあなたがそのように巣立っているかどうか、または少なくとも、私は方法がわからない。また、おそらく[この質問](http://stackoverflow.com/questions/9909399/nested-structured-numpy-array)は関連しています。 –

答えて

1

私はCの構造体をあまり使わないので、これは少し推測です。この定義に

In [125]: SIZE1, SIZE2 = 3,4 

In [127]: dtB=np.dtype([('y',np.uint16),('c',np.uint8,(SIZE2,))]) 
In [128]: np.ones((2,), dtype=dtB) 
Out[128]: 
array([(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])], 
     dtype=[('y', '<u2'), ('c', 'u1', (4,))]) 
In [129]: _.itemsize 
Out[129]: 6 

、このアレイの各レコードは6バイト、yフィールド2、cフィールドの4から成ります。 A定義

In [130]: dtA=np.dtype([('x',np.uint32),('b',dtB,(SIZE1,))]) 
In [131]: np.ones((2,), dtype=dtA) 
Out[131]: 
array([(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])]), 
     (1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])])], 
     dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))]) 
In [132]: _.itemsize 
Out[132]: 22 

の各レコードは、4 xフィールドのバイト、3つのb要素3 * 6を有し、そして

巣。

In [133]: __.tobytes() 
Out[133]: b'\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01' 

そして配列をより面白くしようとしている:

In [136]: A['x']=[1,2] 
In [139]: A['b']['y'] *= 3 
In [141]: A['b']['c'][0]=2 
In [142]: A['b']['c'][1]=3 
In [143]: A 
Out[143]: 
array([(1, [(3, [2, 2, 2, 2]), (3, [2, 2, 2, 2]), (3, [2, 2, 2, 2])]), 
     (2, [(3, [3, 3, 3, 3]), (3, [3, 3, 3, 3]), (3, [3, 3, 3, 3])])], 
     dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))]) 
In [144]: A[0].tobytes() 
Out[144]: b'\x01\x00\x00\x00\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02' 

はあなたのc構造体と一致したものバイト文字列はありますか?

+0

これは完全に機能しました。ありがとうございました! – neekogi

関連する問題