On 27 Feb 2008, at 09:24, Vikrant Singh wrote: > Hello All, > > This is the first time I am working on Ruby and I am not sure if I am > asking very basics of the language. > > > I am working on a tool which is written in Ruby and I need to > implement > a new feature in it. Although itÃÔ a small update still to work and > understand the code I need to learn the basics of Ruby first. > > I am using űrogramming Ruby, 2nd Editionby Dave Thomas as a > reference. Its a good book and I am able to proceed using it. > > Today I got stuck in memory handling code > > Following is what I am doing and need your comments on the same> > 1.Working in a function which receives number of bytes as argument. > 2.I need to allocate memory (double in the size sent in argument) to a > buffer and also initialize all the bits to zero. > > I wrote following code for the last two points> def FunctionName (numBytes) > bufferSize = numBytes*2 > buffer = dl.malloc(bufferSize) > end def FunctionName(numBytes) bufferSize = numBytes * 2 buffer = "\0" * bufferSize end Most of the external interfaces can use strings as sets of binary data, as this is our best binary representation at present. If you use a ruby string, instead of a dl.malloc, the only thing you need to ensure is that the data is not GC'd prematurely. This will happen if there are no references left on the ruby side. I can't comment on the semantics of dl, as I've never used it. > > I am using this dl.malloc after taking reference from existing code. > Here I searched in the book and found that Ruby presents its own APIs > for memory allocation. > I also found that dl is a way of using win32 APIs instead of RubyÃÔ PI. > Which one is better? > Also, after allocation how to make sure that memory is initialized > with > all zeros. > > 3.Set the 10th bit in the buffer > buffer[bufferSize -2] = buffer[bufferSize -2] | 0x4 > > 4.Execute some library calls with this buffer > 5.Clear the buffer again > > I searched the book and found that clear function is used to clear the > content of an array. I am not sure if the same will work with the > dynamically allocated buffer as well. > Buffer.clear > > 6.Execute some library calls again in this buffer > 7.Copy the first half of the buffer in a new buffer and second half of > the buffer in another. > > firstHalf = dl.malloc(numBytes) > secondHalf = dl.malloc(numBytes) > #Copy numBytes©ÏumBytes/2 > memcpy(firstHalf, buffer, numBytes) > #Copy numbytes/2 0 > Memcpy(secondHalf, buffer[0..numBytes/2], numbytes) first_half = buffer[0..half] sec_half = buffer[half..-1] You won't need to memcpy if you're treating the data as a regular ruby tring. > > > Please reply with your view on the same. Please correct me if I am > wrong > somewhere. > -- > Posted via http://www.ruby-forum.com/. >