使用ctypes libc.strlen时总是返回1吗? [英] When using ctypes libc.strlen always returning 1?

查看:68
本文介绍了使用ctypes libc.strlen时总是返回1吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ctypes的简单代码:

I have a simple code using 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 3 uses Unicode for strings. When passed to a C function those will be more than one byte per character, and for ASCII characters one of those bytes will be zero. strlen will stop at the first zero it finds.

我能够在Python 2.7中复制这些结果,以及解决方法:

I'm able to duplicate these results in Python 2.7, along with a fix:

>>> libc.strlen("HELLO")
5
>>> libc.strlen(u"HELLO")
1
>>> libc.strlen(u"HELLO".encode('ascii'))
5

这篇关于使用ctypes libc.strlen时总是返回1吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆