LoginSignup
6
4

More than 5 years have passed since last update.

ctypesでhelloworld

Posted at

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!
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4