11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ctypesの変数についてのメモ

Last updated at Posted at 2019-06-22

変数、ポインタの生成と読み書き

ライブラリの読み込み

import ctypes

通常の変数の生成

i = ctypes.c_uint32(10)  # unsigned int i = 10;
f = ctypes.c_float(25.4)  # float = 25.4;

生成した変数の値を取得

i.value  # 10
f.value  # 25.399999618530273

生成した変数への代入

i.value = 20
f.value = 14.2

生成した変数のポインタを取得

i_p = ctypes.pointer(i)
f_p = ctypes.pointer(f)

ポインタから変数を取得

i_p.contents
f_p.contents

ポインタから変数の値を取得

i_p.contents.value  # 20
f_p.contents.value  # 14.199999809265137

配列の生成と読み書き

1次配列の生成

i_arr = (ctypes.c_int32 * 3)()  # int i[3];

2次配列の生成

i_arr = ((ctypes.c_int32 * 4) * 3)()  # int i[3][4];

配列の読み書き

i_arr = (ctypes.c_int32 * 3)()  # int i[3];
i_arr[0] = 10
print(i_arr[0])  # 10

ctypesで扱える型の一覧

ctypesの型 Cの型 Pythonの型
c_bool _Bool bool (1)
c_char char 1文字のバイト列オブジェクト
c_wchar wchar_t 1文字の文字列
c_byte char int
c_ubyte unsigned char int
c_short short int
c_ushort unsigned short int
c_int int int
c_uint unsigned int int
c_long long int
c_ulong unsigned long int
c_longlong __int64 または long long int
c_ulonglong unsigned __int64 または unsigned long long int
c_size_t size_t int
c_ssize_t ssize_t または Py_ssize_t int
c_float float 浮動小数点数
c_double double 浮動小数点数
c_longdouble long double 浮動小数点数
c_char_p char * (NUL 終端) バイト列オブジェクトまたは None
c_wchar_p wchar_t * (NUL 終端) 文字列または None
c_void_p void * 整数または None

参考

https://qiita.com/everylittle/items/6e18ba23f38502c18f3e
https://docs.python.org/ja/3/library/ctypes.html
http://curlnoodle.hatenablog.com/entry/2013/12/30/221858

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?