简体   繁体   中英

How do I figure out the format for struct.unpack (because I didn't pack in Python)?

I have a C pipe client (pulled directly from the CallNamedPipe example found here ) that, if given the string "first", sends the following message to my Python pipeserver:

b'f\x00i\x00r\x00s\x00t\x00\x00\x00'

The struct documentation gives examples where I did both the packing and unpacking in Python. That means I know the format because I explicitly specified it when I called struct.pack .

Is there some way for me to either a) infer the format from the above output or b) set the format in C the same way I do in Python?

Here's the relevant client code:

    LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\testpipe");
    LPTSTR lpszWrite = TEXT("first");
    fSuccess = CallNamedPipe( 
          lpszPipename,        // pipe name 
          lpszWrite,           // message to server 
    ...

Your C code is not writing a struct to the pipe, it is writing a null-terminated string encoded as little-endian UTF-16 text, which is produced by the TEXT() macro when you compile your Windows program in Unicode mode for an Intel CPU. Python knows how to decode these strings without using the struct module. Try this:

null_terminated_unicode_string = data.decode('utf-16le')
unicode_string = null_terminated_unicode_string[:-1]

You can use decode('utf-16') if your python code is running on the same CPU architecture as the C program that writes the data. You might want to read up on python's unicode codecs .

EDIT: You can infer the type of that data by knowing how UTF-16 and Windows string macros work, but python cannot infer it. You could set the string encoding in C the same way you would in python if you wanted to write some code to do so, but it's probably not worth your time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM