Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

25. Native and COM Interoperability > Mapping a Struct to Unmanaged Memory

Mapping a Struct to Unmanaged Memory

A struct with a StructLayout of Sequential or Explicit can be mapped directly into unmanaged memory. Consider the following struct:

[StructLayout (LayoutKind.Sequential)]
unsafe struct MySharedData
{
  public int Value;
  public char Letter;
  public fixed float Numbers [50];
}

The fixed directive allows us to define fixed-length value-type arrays inline, and it is what takes us into the unsafe realm. Space in this struct is allocated inline for 50 floating-point numbers. Unlike with standard C# arrays, NumberArray is not a reference to an array—it is the array. If we run the following:

static unsafe void Main()
{
  Console.WriteLine (sizeof (MySharedData));
}

the result is 208: 50 4-byte floats, plus the 4 bytes for the Value integer, plus 2 bytes for the Letter character. The total, 206, is rounded to 208 due to the floats being aligned on 4-byte boundaries (4 bytes being the size of a float).


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint