LoginSignup
0
2

More than 3 years have passed since last update.

Pythonでctypesを使ってコールバック関数でchar*を返すには

Last updated at Posted at 2015-03-15

PythonでC言語から呼んでもらう例は、qsortのint型を返す例くらいしか
見つからず、後は難しいWindowsの構造体を返す方法があったような。

今回のコールバックの型

CBFUNC=CFUNCTYPE(c_char_p,c_char_p)
cbfunc=CBFUNC(py_cb_func)

普通に

msg = "Hello, Trusterd.this is Python."
buf = create_string_buffer(msg.encode('UTF-8'))
return buf

だと

Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 302, in 'converting callback result'
TypeError: bytes or integer address expected instead of c_char_Array_32 instance
Exception ignored in: <function py_cb_func at 0x1041dd510>

と、C言語側で戻り値を受けてれるものの、
意図した文字列を受け取ることは出来ませんした。

試行錯誤の結果

msg = "Hello, Trusterd.this is Python."
buf = create_string_buffer(msg.encode('UTF-8'))
c = cast(buf, POINTER(c_char))
return addressof(c.contents)

これで、C言語側に意図した文字列を返すことが出来ました。

ちなみに、通常のC言語側を呼び出す際の引数の指定は

hogefunc(create_string_buffer(msg.encode('UTF-8')))

で問題なく出来ます。

関連記事

0
2
2

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