• Advertisement
Sign in to follow this  

[.net] Making an empty buffer

This topic is 4797 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, This is more of a question for C# than Direct X, but i am using this in a Direct X program and so i am asuming someone else has needed to do this! i am locking a texture using the InternalData.ToPointer method. but i want to copy this data to some other buffer. now i can do this in C++ but in c# how the hell do i make a new byte buffer! note NOT a byte array but a chunk of memory. i am using "unsafe" code so there must be a way.. i just dont know much about c# yet. thanks

Share this post


Link to post
Share on other sites
Advertisement
I'm not sure, but it sounds like you want to allocate a chunk of unmanaged memory. To do this use the System.Runtime.InteropServices.Marshal.AllocHGlobal(int) method. It allocates however many bytes of memory you specify on the unmanaged heap and returns an IntPtr (which can be converted to a void*, char*, etc.). Of course, since the memory is unmanaged, you'll also have to deallocate it when your done with it, which can be done using the System.Runtime.InteropServices.Marshal.FreeHGlobal(IntPtr) method.

Share this post


Link to post
Share on other sites
You can also use the fixed statement to pin some memory in place:

unsafe {
byte[] b = new byte[200];
fixed(byte* bp = b){
//fill it up
}
}

Share this post


Link to post
Share on other sites
Quote:
Original post by turnpast
You can also use the fixed statement to pin some memory in place:
*** Source Snippet Removed ***

This will work well, but keep in mind that while an array is pinned, the garbage collector has to *work around it* as it were to prevent it from being moved around in the managed heap. If you pin an object for a long time, this can incur a performance hit. If you pin an array make sure you do it in as small of segments as you can:

Do this:

while(conditionMet) {

//do stuff

fixed(void* ptr = array) {

//do the stuff that requires the pointer

}

//do other stuff

}


Instead of this:

fixed(void* ptr = array) {

while(conditionMet) {

//do all that stuff

}

}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement