stackalloc of arrays in C#
I have been trying to get some info about stack arrays in C# and only way to allocate this kind of buffer is to use unsafe code
char* buffer = stackalloc char[16];
As a workaround I can make a structure of chars.
struct Buffer16
{
public char c1,c2 //开发者_C百科to 16
}
Is there a way to make a buffer not by creating a new type. Create at runtime.
You can always cast the pointer to primitive type pointers or structures:
char* buffer = stackalloc char[16];
int* i = (int*) buffer;
long* l = (long*) buffer;
byte* b = (byte*) buffer;
Point* p = (Point*) buffer;
So you have all the flexibility. You can also use Marshal.PtrToStructure
and reverse without using unsafe code.
Does this answer your question?
I don't believe there is a way to do it without jumping through hoops.
C# is generally designed to discourage micro-management of memory resources, and tends to go to great pains to make difficult to treat the CLR's memory manager as anything but a black box. A large part of the reason for this is that the memory manager generally does what it does very well, and does it best when you stay out of its way. It's generally good enough that I wouldn't be surprised if there's no real performance benefit to be gained from putting a buffer in the stack instead of the heap, anyway.
精彩评论