1

ctypesを使用した簡単なコードがあります。

Python 3.1.1 (r311:74480, Feb 23 2010, 11:06:41)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> libc.strlen("HELLO")
1
>>> print(libc.strlen("HELLO"))
1

私は何を間違えましたか?

前もって感謝します。

4

4 に答える 4

2

Python 3 は文字列に Unicode を使用します。C 関数に渡されると、文字ごとに 1 バイト以上になり、ASCII 文字の場合、それらのバイトの 1 つがゼロになります。strlen見つかった最初のゼロで停止します。

これらの結果は、修正とともに Python 2.7 で複製できます。

>>> libc.strlen("HELLO")
5
>>> libc.strlen(u"HELLO")
1
>>> libc.strlen(u"HELLO".encode('ascii'))
5
于 2012-06-13T20:50:00.450 に答える
2

引数の型を伝えるのは良い考えです。ctypes間違っている場合は教えてくれます:

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> libc = ctypes.CDLL("msvcrt")
>>> libc.strlen('hello')
1
>>> libc.strlen.argtypes=[ctypes.c_char_p]
>>> libc.strlen('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type

Python 3 では、文字列はデフォルトの Unicode です。 b''構文はバイト文字列であり、これは strlen が機能するものです:

>>> libc.strlen(b'hello')
5

少なくとも Windows では、strlen のワイド バージョンがあります。

>>> libc.wcslen.argtypes=[ctypes.c_wchar_p]
>>> libc.wcslen('hello')
5
于 2012-06-15T05:50:06.040 に答える
0
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> libc = ctypes.CDLL('libc.so.6')
>>> libc.strlen('HELLO')
5

Either your version of Python or gcc or perhaps it needs to be explicitly NUL terminated as in libc.strlen('HELLO\0') ?

于 2012-06-13T20:30:17.197 に答える
0

奇妙な.... b で動作します!.

>>> libc.strlen(b'HELLO')
5
于 2012-06-13T20:35:39.247 に答える