Re: LP_c_ubyte buffer and length to python string?
Mads Kiilerich <[email protected]> Sun, 24 Jul 2011 17:34:59 +0200
| Newsgroups | gmane.comp.python.ctypes |
|---|---|
| Message-ID | <[email protected]> |
Dan Stromberg wrote, On 07/23/2011 11:27 PM: > > I've googled on this for hours, and found nothing that seems close to > what I want to do. > > I have a C function that accepts a preallocated buffer and a pointer > to an integer. It then stashes data in the buffer, and passes back > the buffer's "in use" length in the integer. > > I'm creating the buffer with: > > ctypes_compressed_buffer_char_p = > ctypes.create_string_buffer(maximum_size) > ctypes_compressed_buffer = > ctypes.cast(ctypes_compressed_buffer_char_p, > ctypes.POINTER(ctypes.c_ubyte)) > > Then I create my length with: > > ctypes_compressed_size = ctypes.c_size_t(0) > ctypes_compressed_size_pointer = > ctypes.cast(ctypes.addressof(ctypes_compressed_size), ctypes.c_void_p) > > The length is actually a size_t, but passing a pointer to size_t in > ctypes was giving me type errors, hence the void *. > > Anyway, the function executes without reporting any errors, so I seem > to have my result - in a ctypes format. Printing its type reports > that its an LP_c_ubyte. > > How can I convert the resulting LP_c_ubyte (array) and int to a Python > 2.x str and a 3.x bytes? I assume you want to get the content of the chunk of memory that was allocated by create_string_buffer. The simplest way to get that is ctypes_compressed_buffer_char_p.raw[:length] but you can also do ''.join(chr(x[i]) for i in range(length)) Besides that: It seems strange that you have to cast your buffer and your size_t. ctypes gives you all the power and danger of both Python and C at once, so just because it executes without reporting errors doesn't mean that you got it right. You might want to post a minimal self-contained code snippet that shows what function you are calling and how you are doing it. /Mads ------------------------------------------------------------------------------ Magic Quadrant for Content-Aware Data Loss Prevention Research study explores the data loss prevention market. Includes in-depth analysis on the changes within the DLP market, and the criteria used to evaluate the strengths and weaknesses of these DLP solutions. http://www.accelacomm.com/jaw/sfnl/114/51385063/