The legacy database that I'm interfacing with uses a data buffer to pass rows to applications. To handle this in C#, I wrote a class that provides methods for reading and writing different types in the buffer. Each data file uses one data buffer, but the buffer has to be resized for certain operations. To do this, I added an Allocate method:
public void Allocate(int bytes) {
if (handle != IntPtr.Zero) { // memory has already been allocated
Marshal.FreeHGlobal(handle);
}
handle = Marshal.AllocHGlobal(bytes);
}
That was before I noticed ReAllocHGlobal, however. Now I'm wondering if I should do this:
public void Allocate(int bytes) {
if (handle != IntPtr.Zero) { // memory has already been allocated
handle = Marshal.ReAllocHGlobal(handle, (IntPtr)bytes);
} else { // this is a brand new data buffer
handle = Marshal.AllocHGlobal(bytes);
}
}
I think the first method looks cleaner, but which is the best to use? My first thought was that ReAllocHGlobal makes the most sense (since it's specifically for resizing an existing block of memory), but I'm not 100% certain.