[英]Python ctypes union, string, str, byte: three Pythons, three different results
A colleague was asked to provide a starting point for socket client and server applications that I could adapt to our customer's needs. 要求一位同事为我可以适应客户需求的套接字客户端和服务器应用程序提供一个起点。 He provided something a lot fancier than I expected, and provided an excellent lesson in Python programming for me.
他提供的东西比我想象的要好得多,并且为我提供了关于Python编程的精彩课程。
But he targeted his programs to Python 2.7. 但是他将程序定位于Python 2.7。 I have spent my entire time at this company trying to drag it into the 20th century.
我在这家公司度过了我的全部时间,试图将其拖入20世纪。 (Note that I didn't say 21st.) I want to use Python 3.2 (not 3.5 because everybody but me uses PythonWin, which won't work with 3.5. I use PyCharm).
(请注意,我没有说21号。)我想使用Python 3.2(而不是3.5,因为除我以外的所有人都使用PythonWin,该工具不适用于3.5。我使用PyCharm)。
The code supplied by my colleague uses the ctypes module's Structure and Union classes. 我的同事提供的代码使用ctypes模块的Structure和Union类。 In Python 3.2, the first line of the
__init__
method throws this exception: TypeError: expected string, str found. 在Python 3.2中,
__init__
方法的第一行引发此异常:TypeError:预期的字符串,找到的str。 In Python 3.5, the error is "TypeError: expected bytes, str found." 在Python 3.5中,错误为“ TypeError:预期的字节,找到了str”。 In Python 2.7, there is no error and the code works.
在Python 2.7中,没有错误并且代码可以正常工作。
This is my first encounter with the ctypes module, and I only met Python 3 when I began this project. 这是我第一次接触ctypes模块,当我开始这个项目时,我才遇到Python 3。 Can someone tell me what I need to do to get this to work?
有人可以告诉我我需要做些什么才能使它正常工作吗?
Here's the code: 这是代码:
class AliveMsg(Structure):
"""
"""
_pack_ = 1
_fields_ = [("Header", MsgHeader), # Header
("EndFlag", c_char * 1)] # End Flag always '#'
class TransAlive(Union):
length = 49
_pack_ = 1
_fields_ = [("Struct", AliveMsg),
("Message", c_char * 49),
("Initialize", c_char * 49)]
def __init__(self):
self.Initialize = ' ' * 49
self.Struct.Header.START_FLAG = '*'
self.Struct.Header.SEP1 = ';'
self.Struct.Header.SEP2 = ';'
self.Struct.Header.SEP3 = ';'
self.Struct.Header.SEP4 = ';'
self.Struct.Header.HEADER_END = 'Data:'
self.Struct.EndFlag = '#'
Use byte strings instead of Unicode strings for c_char
. c_char
使用字节字符串而不是Unicode字符串。 Unicode strings are the default in Python 3, but byte strings are the default in Python 2. For example: Unicode字符串是Python 3中的默认值,但字节字符串是Python 2中的默认值。例如:
self.Initialize = b' ' * 49
If you assign text to Message
, to use non-ASCII you can use a Unicode string but encode it to a byte string in an appropriate encoding: 如果将文本分配给
Message
,以使用非ASCII,则可以使用Unicode字符串,但可以使用适当的编码将其编码为字节字符串:
self.Message = 'Some Chinese: 马克'.encode('utf8')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.