ctypes - c_buffer

Thomas Heller theller at python.net
Tue May 6 05:00:22 EDT 2003


"Roman Yakovenko" <romany at actimize.com> writes:

> 	Good morning. I am using ctypes 0.6.0 library and I think I
> found small defect in it.
> The problem is - there is no simple way to find out the length of null
> terminated string. 
> If I wrong correct me please.
> 
> Consider next situation:
> C function:
> 	 void dosmth( const char *from, char *to ); //this function
> writes smth into to
> 
> In Python:
> 	x = c_buffer('\000', 128)
> 	dosmth( "Hello world", x )
> 	
> Now the only way to know length of x as string is
> 
> str_x = []
> for i in x.value:
>     str_x.append(i)
>     if not i:
>         break
> str_x = ''.join(str_x)
> 
> After this you may take the length of the string. 
> This way is not too bad for C, but I write my programs in Python.
> 
> So the question is: Am I wrong or missed smth?
The string is already exposed as the .value or the .raw property.
.value is the string up to the first NUL character, .raw is the whole
buffer contents:


from ctypes import *

sprintf = cdll.msvcrt.sprintf

x = c_buffer("\000", 8)

sprintf(x, "Spam")

print repr(x.value)
print repr(x.raw)


This script prints:

'Spam'
'Spam\x00\x00\x00\x00'

Thomas




More information about the Python-list mailing list