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 函数时,每个字符将超过一个字节,对于 ASCII 字符,其中一个字节将为零。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

您的 Python 或 gcc 版本,或者它可能需要显式 NUL 终止,如libc.strlen('HELLO\0')

于 2012-06-13T20:30:17.197 回答
0

奇怪....与 b 它的作品!

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