3

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?

Gabe
  • 84,912
  • 12
  • 139
  • 238
Jacob Quisenberry
  • 1,131
  • 3
  • 20
  • 48

1 Answers1

10

Use Marshal.SizeOf instead.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Thank you. I ended up using `wcex.cbSize = (uint)Marshal.SizeOf(typeof(PlatformInvokeUSER32.WNDCLASSEX));` – Jacob Quisenberry Oct 25 '11 at 22:05
  • Things change over time, and now MS recommends the generic form of this method, e.g. `(uint)Marshal.SizeOf();` https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.sizeof?view=netcore-3.1 – Paul Williams May 14 '20 at 17:22