Re: [ctypes-users] Null terminators..
Brought to you by:
theller
|
From: John S. <ga...@ga...> - 2003-07-31 21:02:53
|
Well, after some much hacking, I came up with the following solution to my
non-null-terminated string problem... Below is some sample code.. Not sure
if I totally like the idea, but it works.. Is there a way to get the size
of a field (to eliminate the seperate storing of the lengths) ??
from ctypes import *
def create__setattr__():
def s( self, key, value ):
# bizzare stuff for string that are not null terminated
if type( value ) is str:
# figure out the offset.
tempP = addressof( self )
# add in the offsets..
for field in self._fields_:
if field[ 0 ] == key:
fieldsize = self.lengths[key]
break
tempP = tempP + self.lengths[key]
# field[1] has the data type for what I need..
tempBuff = field[1].from_address( tempP )
tempValue = c_char_p( value )
cdll.msvcrt.memcpy( byref(tempBuff),
tempValue,
self.lengths[key] )
else:
Structure.__setattr__( self, key, value )
return s
fields = [ ( "test1", c_char * 6 ), ( "test2", c_int ) ]
fieldLen = {"test1":6, "test2":4 }
recObject = type( "RECORD", (Structure,),
{'_fields_':fields,
'lengths':fieldLen,
'__setattr__':create__setattr__()
} )
rec = recObject()
rec.test1 = "AAAAAB"
rec.test2 = 7
print rec.test1
print rec.test2
rec.test1 = "BBBBBC"
print rec.test1
print rec.test2
> "John Sutherland" <ga...@ga...> writes:
>
>> A new question..
>>
>> In that struct that was dynamicly generated, I have character strings
>> that
>> are -not- null terminated (based on some 1985 programming, they wanted
>> to
>> save memory.. Hey, it still works :) )..
>>
>> More of less, the structure looks like this:
>>
>> struct
>> {
>> char field1[2];
>> char field2[4];
>> }
>>
>> So if I put "11" into field1 and "2222" into field2, I should get
>> something in memory like:
>>
>> "112222"
>>
>> ctypes seems to read this ok.. But when I try to field1 = "JS", it tells
>> me that its too long.. I assume that it expects a null terminator.. Is
>> there any way to handle this type of situation?
>
> It doesn't seem so, at the moment. It is currently discussed in other
> threads.
>
> Thomas
>
>
>
> -------------------------------------------------------
> This SF.Net email sponsored by: Free pre-built ASP.NET sites including
> Data Reports, E-commerce, Portals, and Forums are available now.
> Download today and enter to win an XBOX or Visual Studio .NET.
> http://aspnet.click-url.com/go/psa00100003ave/direct;at.aspnet_072303_01/01
> _______________________________________________
> ctypes-users mailing list
> cty...@li...
> https://lists.sourceforge.net/lists/listinfo/ctypes-users
>
>
--John
|