ユーザー定義の C 言語ライブラリの使用¶
PyFIE では FIE(C 言語) だけでなく、任意の C 言語ライブラリのバインディングを追加することが可能です。
本稿では add_library()
関数によりユーザー定義の C 言語ライブラリを使用する例を示します。
注釈
本節では簡単のため、下記いずれかの環境であることを前提とします。
OS が Ubuntu 18.04 LTS 64 bit であり、 gcc がインストール済みである。
OS が Windows 10 64 bit であり、 Visual Studio 2019 がインストール済みである。
以下のような C 言語ソースコード sample_user_defined_library.c から生成されるライブラリの Python からの利用を考えます。
// 共有ライブラリの設定
#ifdef _MSC_VER
// Windows
#define DLL_EXPORT __declspec(dllexport)
#define API_CALL __stdcall
#else
// Linux
#define DLL_EXPORT
#define API_CALL
#endif
// define
#define MY_VALUE 42
// enum
enum MYENUM
{
MYENUM_1 = 1,
MYENUM_MINUS1 = -1
};
// function
DLL_EXPORT int API_CALL a_square_function(int x)
{
return x * x;
}
// struct
typedef struct
{
int field;
} MY_STRUCT;
// union
union
{
int value_int;
double value_dbl;
} MY_UNION;
このソースコードに対して次のコマンドによりライブラリバイナリファイル sample_user_defined_library.{so,dll} を作成します。
# Ubuntu の場合
gcc -shared -fPIC -o sample_user_defined_library.so sample_user_defined_library.c
# Windows の場合
cl /LD sample_user_defined_library.c /link
このライブラリバイナリに対応する ライブラリ定義ファイル sample_user_defined_library.json を以下のように作成します。
{
"DECL": {
"DEFINE": [
{
"name": "MY_VALUE",
"val": 42
}
],
"ENUM": [
{
"name": "MY_ENUM",
"contents": [
{
"name": "MYENUM_1",
"val": 1
},
{
"name": "MYENUM_MINUS1",
"val": -1
}
]
}
],
"FUNCTIONS": [
{
"name": "a_square_function",
"args": [
{
"name": "x",
"type": "C_int"
}
],
"restype": "C_int"
}
],
"STRUCT": [
{
"name": "MY_STRUCT",
"members": [
{
"name": "field",
"type": "C_int"
}
]
}
],
"UNION": [
{
"name": "MY_UNION",
"members": [
{
"name": "value_int",
"type": "C_int"
},
{
"name": "value_dbl",
"type": "C_double"
}
]
}
]
}
}
作成したライブラリバイナリファイル sample_user_defined_library.{so,dll} とユーザー定義のライブラリ定義ファイル sample_user_defined_library.json をカレントディレクトリに設置してください。
下記のようにPythonスクリプトを実行することで、作成した C 言語ライブラリを使用することができます。
import pyfie
# ユーザー定義のライブラリを読み込み
pyfie.add_library("sample_user_defined_library.so",
"sample_user_defined_library.json")
# Windows 環境では *.so ではなく *.dll を読み込む
# pyfie.add_library("sample_user_defined_library.dll", "sample_user_defined_library.json")
# ユーザー定義のライブラリを使用
print(pyfie.MY_VALUE) # => 42
print(pyfie.MYENUM_1) # => 1
print(pyfie.a_square_function(5)) # => 25
st = pyfie.MY_STRUCT(field=8)
print(st.field) # => 8