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