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’s a small update still to work and
understand the code I need to learn the basics of Ruby first.
I am using “Programming Ruby, 2nd Edition†by Dave T. 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
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’s API.
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…numBytes/2
memcpy(firstHalf, buffer, numBytes)
#Copy numbytes/2 … 0
Memcpy(secondHalf, buffer[0…numBytes/2], numbytes)
Please reply with your view on the same. Please correct me if I am wrong
somewhere.