在c#中使用托管结构的sizeof

本文关键字:结构 sizeof | 更新日期: 2023-09-27 18:12:28

我正在尝试将c++代码移植到c#。该代码旨在使用RegisterClassEx注册一个窗口类。

c++代码有一个对象WNDCLASSEX wcex。对象wcex有一个属性

wcex.cbSize = sizeof(WNDCLASSEX);
在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;
    }

我已经尝试使用

获取尺寸
wcex.cbSize = (uint)sizeof(WNDCLASSEX);

包含该语句的函数声明为

unsafe private void

我希望unsafe能使声明生效。但是,我在IDE中得到这个错误:

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

我可以将结构变为非托管结构吗?如果有,怎么做?有没有一种方法可以使用sizeof而不使结构失控?有。net版本的sizeof可以工作吗?

在c#中使用托管结构的sizeof

使用Marshal.SizeOf