在C#声明的C结构与工会 [英] Declaring C struct with union on C#

查看:171
本文介绍了在C#声明的C结构与工会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要声明_WAITCHAIN​​_NODE_INFO结构声明在我的code - 要WCT使用。
我试图从遵循教程:

I want to declare _WAITCHAIN_NODE_INFO struct declaration in my code - for WCT usage. I've tried to follow the tutorials from :

https://msdn.microsoft.com /en-us/library/eshywdt7(v=vs.110).aspx

但后来我每次使用电话WCT和我的管理结构声明,我得到堆损坏。

But every time then I use WCT call with my managed struct declaration I get heap corruption.

typedef struct _WAITCHAIN_NODE_INFO {
  WCT_OBJECT_TYPE   ObjectType;
  WCT_OBJECT_STATUS ObjectStatus;
  union {
    struct {
      WCHAR         ObjectName[WCT_OBJNAME_LENGTH];
      LARGE_INTEGER Timeout;
      BOOL          Alertable;
    } LockObject;
    struct {
      DWORD ProcessId;
      DWORD ThreadId;
      DWORD WaitTime;
      DWORD ContextSwitches;
    } ThreadObject;
  };
} WAITCHAIN_NODE_INFO, *PWAITCHAIN_NODE_INFO;

MSDN:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681422(v=vs.85).aspx

这并不让我堆损坏唯一的声明是这样的:

The only declaration that doesn't get me a heap corruption is this:

public struct WAITCHAIN_NODE_INFO
{
    public WCT_OBJECT_TYPE ObjectType;
    public WCT_OBJECT_STATUS ObjectStatus;
}

显然,我是缺少在这里LockObject和ThreadObject结构的结合。

Obviously, I am missing here the union of LockObject and ThreadObject structs.

我如何转换这个C结构到C#托管申报?

How can I convert this C struct to C# managed declaration?

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

声明两个结构在工会作为通常的方式C#结构。然后声明一个类型的工会,使用显式的布局。

Declare the two structs in the union as C# structs in the usual way. Then declare a type for the union, using an explicit layout.

[StructLayout(LayoutKind.Explicit)] 
public struct _WAITCHAIN_NODE_INFO_UNION
{
    [FieldOffset(0)]
    _WAITCHAIN_NODE_INFO_LOCK_OBJECT LockObject;
    [FieldOffset(0)]
    _WAITCHAIN_NODE_INFO_THREAD_OBJECT ThreadObject;
}

然后工会添加到您的结构:

Then add the union to your struct:

[StructLayout(LayoutKind.Sequential)]
public struct WAITCHAIN_NODE_INFO
{
    public WCT_OBJECT_TYPE ObjectType;
    public WCT_OBJECT_STATUS ObjectStatus;
    public _WAITCHAIN_NODE_INFO_UNION Union;
}

在覆盖这样的对象,额外的要求放置在所涉及的类型。不能覆盖包含字符串或例如数组的类型。所以字符数组将必须被实现为值类型,例如href=\"https://msdn.microsoft.com/en-gb/library/zycewsya.aspx\" rel=\"nofollow\">固定阵列。这是不方便与工作,但MS没有考虑定义与C#的类型。

When you overlay objects like this, extra requirements are placed on the types involved. You cannot overlay a type containing a string or an array for instance. So the character array will have to be implemented as a value type, for instance a fixed array. This is inconvenient to operate with but MS did not define the types with C# in mind.

这篇关于在C#声明的C结构与工会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆