在 C# 中使用托管结构的 sizeof
我正在尝试将 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 中收到此错误:
无法获取托管类型的地址、获取大小或声明指向托管类型的指针 ('CaptureScreen.PlatformInvokeGDI32.WNDCLASSEX')
我可以创建结构吗进入非托管结构?如果是这样,怎么办? 有没有办法使用 sizeof 而不使结构不受管理? 有没有可以使用的 .NET 版本的 sizeof ?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Marshal.SizeOf
相反。Use
Marshal.SizeOf
instead.