2017-06-14 10 views
0

私はPythonのcffiライブラリを使用して構造体をインスタンス化しようとしています。私は自分の.hファイルから構造体をインスタンス化したいと思います。また、標準ライブラリの構造体もインスタンス化したいと思います。python cffiで構造体をインスタンス化するには?

import datetime 
import os 
from cffi import FFI 

clib = None 

script_path = os.path.dirname(os.path.realpath(__file__)) 

ffi = FFI() 
with open(os.path.join(script_path, 'myheader.h'), 'r') as myfile: 
    source = myfile.read() 
    ffi.cdef(source) 
clib = ffi.dlopen('mylib') 

# these all fail 
ffi.new("struct tm") 
ffi.new("struct tm[]", 1) 
ffi.new("struct tm *") 
ffi.new("struct mystruct") 

答えて

1

ffi.new("struct mystruct")は、おそらくffi.new("struct mystruct *")を意味します。

struct tmは、おそらくcdef()に定義されていません。つまり、あなたのケースでは、myheader.hには記載されていません。共通の標準ヘッダーのいずれかに入っていても、使用する前にcdef()に定義する必要があります。

set_source()(APIモード)を使用する方が良いでしょう。おおよその定義はstruct tmです。以下のようなもの:

struct tm { 
    int tm_sec; 
    int tm_min; 
    int tm_hour; 
    int tm_mday; 
    int tm_mon; 
    int tm_year; 
    ...;  /* literally a "..." here */ 
}; 

あなたはdlopen()(ABIモード)を使用する場合は、代わりにあなたのプラットフォームのヘッダーに見られるように、まったく同じ宣言を使用する必要があります。その結果、移植性が低下します。

関連する問題