Dynamic Stack Allocation

>> Wednesday, October 21, 2009


You want to dynamically allocate memory from stack ?

Now use DllImport and stackalloc to implement this function.
Remember that the allocated memory block doesn't participate into the garbage collector's process.

using System;
using System.Runtime.InteropServices;
namespace StackAllocation
{
 class StackAllocator
{ 
[DllImport("kernel32.dll")]
  static extern unsafe bool GetComputerNameW(char* name, ref ulong size);
  [STAThread]
  static unsafe void Main(string[] args)
  {
   ulong size = 256;
   char * name = stackalloc char[(int)size];
   bool success = GetComputerNameW(name, ref size)
   for(uint i = 0; i < size; i++, name++)
   {
    System.Console.Write(*name);
   }
   System.Console.WriteLine();
  }
 }
}

0 comments: