LoginSignup
0
2

More than 3 years have passed since last update.

python2.7 と python3.7 と ctypes

Last updated at Posted at 2021-04-16

python2.7 で動いていたプログラムを python3.7 で動かそうとすると時々変なことが起こる。

ctypes

C言語で記述されたライブラリを他の言語から利用したいことがある。
python では ctypes というモジュールが標準で用意されており、これを利用すればC言語のソースコードに手を加えることなく python から利用することができる。

問題

例えば、以下のようなC言語のプログラムがあり、これを python で動かしたいとする。
単に引数で与えられた文字列を標準出力するプログラムである。

printstr.c
#include <stdio.h>

void printstr(char* str)
{
  printf("%s\n", str);
}

これを libprintstr.so として動的リンクができるようにコンパイルする。gcc なら以下のように。

gcc -c -fPIC printstr.c
gcc -fPIC -shared -o libprintstr.so printstr.o

以下のように python から利用することができる。

ctype.py
from ctypes import *

lib = cdll.LoadLibrary("./libprintstr.so")
str = "hoge"
lib.printstr(str)

python2.7, python3.7 での実行結果はそれぞれ以下の通り。
見ての通り、python3.7 では意図しない結果となっている。

python2.7
hoge
python3.7
h

対応

ctype.py
from ctypes import *

lib = cdll.LoadLibrary("./libprintstr.so")
str = "hoge".encode('utf-8')
lib.printstr(str)
python3.7
hoge
0
2
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
0
2