Python Ctypes空终止字符串块 [英] Python Ctypes Null Terminated String Block

查看:94
本文介绍了Python Ctypes空终止字符串块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 CreateProcessWithLogonW 的ctypes实现,并且一切正常好吧,除了我无法弄清楚如何处理此部分:

I am using a ctypes implementation of CreateProcessWithLogonW, and everything works well except I cannot figure out how to handle this section:


指向新进程的环境块的指针。如果此参数为NULL,则新进程将使用调用进程的环境。

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

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'

但是我还是用它做一个ctypes变量,它会截断信息:

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')

如何正确传递lpEnvironment信息?

How can I pass the lpEnvironment information correctly?

推荐答案

据我所知,整个字符串确实在一个方向上正确地通过了 ctypes 边界,但是在返回的途中被截断了。

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'

不幸的是(至少对我来说,Linux上的Python 2.6.5) create_unicode_buffer 的结果没有 .raw 属性。但是,

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'

工作正常。

这篇关于Python Ctypes空终止字符串块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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