Jacob Quisenberry
Jacob Quisenberry

Reputation: 1199

Using sizeof a Managed Structure in C#

I am trying to port C++ code to C#. The code is meant to register a window class using RegisterClassEx.

The C++ code has an object WNDCLASSEX wcex. Object wcex has a property

wcex.cbSize = sizeof(WNDCLASSEX);

In C#, I have defined the structure as

    [StructLayout(LayoutKind.Sequential)]
    public struct WNDCLASSEX
    {
        public uint cbSize;
        public uint style;
        [MarshalAs(UnmanagedType.FunctionPtr)]
        public PlatformInvokeGDI32.WNDPROC lpfnWndProc;
        public int cbClsExtra;
        public int cbWndExtra;
        public IntPtr hInstance;
        public IntPtr hIcon;
        public IntPtr hCursor;
        public IntPtr hbrBackground;
        public string lpszMenuName;
        public string lpszClassName;
        public IntPtr hIconSm;
    }

I have tried to get the size using

wcex.cbSize = (uint)sizeof(WNDCLASSEX);

The function containing this stament is declared as

unsafe private void

I hoped the unsafe would make the statment work. However, I get this error in the IDE:

Cannot take the address of, get the size of, or declare a pointer to a managed type ('CaptureScreen.PlatformInvokeGDI32.WNDCLASSEX')

Can I make the structure into an unmanaged structure? If so, how? Is there a way to use sizeof without making the structure unmanaged? Is there a .NET version of sizeof that would work?

Upvotes: 3

Views: 2544

Answers (1)

Gabe
Gabe

Reputation: 86768

Use Marshal.SizeOf instead.

Upvotes: 11

Related Questions