python - 使用 ctypes libc.strlen 时总是返回 1?

标签 python python-3.x ctypes

我有一个使用 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

我做错了什么?

提前致谢。

最佳答案

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

关于python - 使用 ctypes libc.strlen 时总是返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022571/

相关文章:

python - 使用 ctypes 将字符串从 Python 传递到 C 共享库的问题

python - 在python中调用C程序函数-段错误

python - cublasXt 矩阵乘法在 C++ 中成功,在 Python 中失败

python - 运行时错误: as_numpy_iterator() is not supported while tracing functions

python - Pygame Beat-Em-Up 游戏//敌人攻击计时器永远不会达到零

python - Python3 中德语元音变音的编码/解码

python - python 中的 gcloud 和 google-cloud 模块有什么区别

python - 如何对两个文件执行错误处理?

python - 比较元素不按顺序排列的元组

python - ^H^?在 python