From: Jacob Repp Date: 2006-02-22T04:19:07+09:00 Subject: Re: Question about String.unpack I'm curious about binary protocol parsing in ruby and have scratched around for some kind of BinaryReader-ish interface for strings. Seems like you could solve this if you know that your struct is in a string you could say: str = fd.sysread(n) name = str.read_str(30) size = str.read_double age = str.read_int stuff = str.read_c I was going to write a native extension to do this after I finish my current Ruby/AIO extension project. Unless there is something that does this already (maybe in a cleaner/more ruby-ish way?) On 2/21/06, Logan Capaldo wrote: > > On Feb 21, 2006, at 9:28 AM, Eric Jacoboni wrote: > > > Hi, > > > > Say i've a C struct like that: > > > > typedef struct { > > char name[30]; > > double size; > > int age; > > char stuff; > > } enreg_t; > > > > This record is written in a file that i want to re-read with a Ruby > > script (just a toy example... to understand). > > > > I've not found a "clean" way to unpack such a record... > > > > My C compiler gives me a total sizeof of 48, so i use a > > fd.sysread(48).unpack(A32dIC) to re-read. But that seems rather > > 'tricky' (i suppose we don't have always such a > > information). Furthermore, the first element is completed with > > garbage if the name field have less than 30 "useful" chars ("Doe", > > for example). > > > > I'm sure i'm missing something but i've not managed to find the right > > way to do that. > > > > Any clue? > > -- > > Eric Jacoboni, ne il y a 1443970729 secondes > > > > there isn't really a "clean" way to do this, since you are doing > something inherently un-clean. > However, to fix the string issue, a possible solution is: > > str.gsub!(/\000.*/, '') > > assuming of course that name is a c-string. > > >