C# Struct Sizes

I’ve been banging my head against trying to get C# to talk to a .dll written in straight C for the past few days. I finally got a grip on passing basic data types, and pointers to basic data types, to/from my .dll, but I started getting garbage when passing pointers to structs and arrays of structs.

I wrote a master sanity check C# program and C .dll to demonstrate the correct methods for getting structs, pointers to structs, and arrays of structs into the .dll functions, and as soon as I clean it up and comment it I’ll post it.

One of my favorite sanity check tools in C is the sizeof() function, which tells you the size in bytes of a data type or struct. Well, C# has a sizeof() function, too, but it requires some verbosity to get the size of a struct out of it. It must have something to do with C# structs being memory managed. There are a few StackOverflow posts and other blog posts about how to do this, but they’re all overly complex or beyond the scope of simply getting the struct size, so here’s my take on it.

Here’s a small program that demonstrates how to get the size of C# structures.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace CSStructSize
{
    class Program
    {
        public struct SimpleStruct
        {
            public int firstInt;
            public int secondInt;
        }

        public struct ComplexStruct
        {
            public char firstChar;
            public char secondChar;
            public long firstLong;
            public short firstShort;
            public char thirdChar;
            public char fourthChar;
        }
        
        static void Main(string[] args)
        {
            Console.WriteLine("\nSize of C# char is: {0}", sizeof(char));
            Console.WriteLine("Size of C# short is: {0}", sizeof(short));
            Console.WriteLine("Size of C# int is: {0}", sizeof(int));
            Console.WriteLine("Size of C# long is: {0}", sizeof(long));
            Console.WriteLine("Size of SimpleStruct: {0}", Marshal.SizeOf(typeof(SimpleStruct)));
            Console.WriteLine("Size of ComplexStruct: {0}", Marshal.SizeOf(typeof(ComplexStruct)));
            Console.ReadLine();
        }
    }
}

The output is:


Size of C# char is: 2
Size of C# short is: 2
Size of C# int is: 4
Size of C# long is: 8
Size of SimpleStruct: 8
Size of ComplexStruct: 24

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s