2011-03-14 51 views
1

我试图用Python的zlib的输出输出到C++字符串。这里的问题与Python zlib output, how to recover out of mysql utf-8 table?非常相似,不同之处在于我的python脚本生成一个C++头文件,其中压缩数据应该以字符串形式存储。但是,由于特殊字符和原始字节,我无法让C++将其作为字符串读取。之所以我不能将它写入文件,然后返回到C++程序,是因为这可能是一个驱动程序组件,因此不允许读取文件。 这是我正在尝试的一个小例子。蟒蛇zlib的输出到C++字符串


compressed_string = zlib.compress("This is a huge string. Around 263KB") 
fptr = open('my_header.h', 'w') 

content = "#ifndef __HEADER_DEFS__\n\ 
#define __HEADER_DEFS__\n\ 
\n\ 
#include \n\ 
\n\ 
std::string binary_compressed = \"%s\" \n\ 
\n\ 
#endif" % compressed_string 

fptr.write(content) 
fptr.close() 

不过,我压缩串是一个巨大的数据,不像比如我在这里给出的,因此我增加了屏幕截图的那种,我在实际的例子越来越字符。

请看一看http://tinypic.com/r/1078lxw/7的屏幕截图。 谢谢

回答

3

你需要escape the non-printable characters在字符串中使用八进制表示法。

例如,

import string 
.... 
safe_string = "" 
for ch in compressed_string: 
    if ch in string.printable and ch != '\\': 
     safe_string += ch 
    else: 
     safe_string += "\%o" % ord(ch) 
content = ".....\"%s\" ...." % safe_string 

(它劝避免十六进制表示法,因为这可以是遵循转义字符可能是合法的十六进制数字,这将破坏东西可变长度和打印字符)

+0

注意'\'仍还可印刷将引起当由C/C++编译器解析逸出。 – 2011-03-15 15:38:12

+0

@Mark B thx固定 – Will 2011-03-15 16:32:32

+0

非常感谢。该工程 – ssarangi 2011-03-16 14:20:46

2

如果你想二进制数据嵌入到一个C++程序,将Unix的xxd -i命令的帮助?

这将生成包含输入的二进制文件的char数组表示C头文件。

+0

即使没有xxd,在python中生成char数组也很简单。 – 2011-03-15 03:02:55