Python Ctypes Null Terminated String Block
I am using a ctypes implementation of CreateProcessWithLogonW, and everything works well except I cannot figure out how to handle this section:
A pointer to an environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.
An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form:
name=value\0
To generated the raw string I execute the following:
lpEnvironment = '\0'.join(['%s=%s' % (k, os.environ[k]) for k in os.environ]) + '\0\0'
print lpEnvironment
'XAUTHORITY=/home/username/.Xauthority\x00MUTT_DIR=/home/username/.mutt\x00LASTDIRFILE=/home/username/.lastpwd-geany\x00LOGNAME=username\...\x00\x00'
However run I make a ctypes variable out of it, it truncates the information:
ctypes.c_wchar_p(lpEnvironment)
c_wchar_p(u'XAUTHORITY=/home/username/.Xauthority')
How can I pass the lpEnvironment information co开发者_运维技巧rrectly?
As far as I can tell, the whole string does get passed across the ctypes
boundary correctly in one direction, but gets truncated on the way back.
>>> ctypes.create_string_buffer('abc\0def').value
'abc'
>>> ctypes.create_string_buffer('abc\0def').raw
'abc\x00def'
Unfortunately (at least for me, Python 2.6.5 on Linux) the result of create_unicode_buffer
doesn't have a .raw
property. However,
>>> ctypes.wstring_at(ctypes.create_unicode_buffer(u'abc\0def), 7)
u'abc\x00def'
works as expected.
精彩评论