3

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 //to 16
}

Is there a way to make a buffer not by creating a new type. Create at runtime.

7
  • 2
    Are you sure you need to allocate your arrays on the stack? Commented Nov 23, 2010 at 23:05
  • 4
    There isn't much point in trying to turn C# into C. Might as well use C. But it doesn't stop you from doing so. You already know the incantations. Commented Nov 23, 2010 at 23:16
  • 2
    BTW: A char in C# represents a Unicode character. The data type that represents an 8-bit unsigned integer is called byte. Commented Nov 23, 2010 at 23:17
  • 4
    Allocation of reference types in .NET is fairly cheap on average, as the heap is compacted during collection. There is no need to fear temporary objects or even temporary buffers; it's very rare that this will be your bottleneck. Commented Nov 23, 2010 at 23:18
  • 1
    @Hans stackalloc is great since you do not have to worry about GC and pinning. That is one reason I would use and it is lightining fast for pointer operations. Commented Nov 23, 2010 at 23:23

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I know about the unsafe but I do not want to use it. For instance I cant on WP7 CF. Thx for the tip with casting, didn't know that.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.