在C#中使用托管结构的大小

Jac*_*rry 1 c# unmanaged managed sizeof

我试图将C++代码移植到C#.该代码用于注册窗口类RegisterClassEx.

C++代码有一个对象WNDCLASSEX wcex.对象wcex有一个属性

wcex.cbSize = sizeof(WNDCLASSEX);
Run Code Online (Sandbox Code Playgroud)

在C#中,我将结构定义为

    [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;
    }
Run Code Online (Sandbox Code Playgroud)

我试图使用大小

wcex.cbSize = (uint)sizeof(WNDCLASSEX);
Run Code Online (Sandbox Code Playgroud)

包含此stament的函数声明为

unsafe private void
Run Code Online (Sandbox Code Playgroud)

我希望unsafe这会使法规有效.但是,我在IDE中收到此错误:

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

我可以将结构化为非托管结构吗?如果是这样,怎么样?有没有办法使用sizeof而不使结构不受管理?是否有适用于sizeof的.NET版本?