ctypesで簡単なCのコードをPythonから呼び出してみます.
Cのコードのコンパイル
test.c
#include <stdio.h>
void hello_world(void)
{
printf("Hello, world!\n");
}
これを以下のコマンドでコンパイルし,共有ファイルにします.
gcc test.c -shared -fPIC -o libtest.so
Pythonからの呼び出し
ctypes_test.py
import ctypes
libc = ctypes.cdll.LoadLibrary('./libtest.so')
libc.hello_world()
以下のコマンドで実行できます
python3 ctypes_test.py
実行結果
Hello, world!