将 int 复制到结构体对象

本文关键字:结构体 对象 复制 int | 更新日期: 2023-09-27 18:36:12

我在C++中有一个结构定义

如下
typedef struct                                                                                      
{
    unsigned __int32   SetCommonPOP:1;
    unsigned __int32   SetCommonSVP:1;
    unsigned __int32   SetCommonUHDP:1;
    unsigned __int32   SetCommonMHDP:1;
    unsigned __int32   MinPwdLength:8;
    unsigned __int32   MaxPwdLength:8;
    unsigned __int32   StoredHdpBackups:8;
} HPM_PWD_CONSTRAINTS;

我将其翻译成 c#,如下所示

[StructLayout(LayoutKind.Explicit, Size=28, CharSet=CharSet.Ansi)]
public struct HPM_PWD_CONSTRAINTS                                                                                   
{
    [FieldOffset(0)] public uint   SetCommonPOP;
    [FieldOffset(1)] public uint   SetCommonSVP;
    [FieldOffset(2)] public uint   SetCommonUHDP;
    [FieldOffset(3)] public uint   SetCommonMHDP;
    [FieldOffset(4)] public uint   MinPwdLength;
    [FieldOffset(12)] public uint   MaxPwdLength;
    [FieldOffset(20)] public uint   StoredHdpBackups;
};

我正在转换为 c# 的 c++ 代码定义了此结构的对象 PWD,并将 int x 的值传递给此对象。

*((uint*)&PWD) = x;

这是如何工作的?在此之后,结构对象的值是多少?如何将其转换为 C#?

将 int 复制到结构体对象

C++结构定义单个 32 位无符号整数的位。SetCommonPOP字段实际上是四字节结构中最低有效位。

即使使用 FieldOffset 也无法将其直接转换为 C#。相反,应将该值视为uint并执行位操作以读取单独的字段。

这是一个链接,应该可以更好地解释C++中的位字段,http://msdn.microsoft.com/en-us/library/ewwyfdbe.aspx

此代码不安全地将结构指针转换为指向uint的指针,然后将指定的uint写入该位内存。

这将覆盖重叠字段的前四个字节以保存uint的值。

unsafe 方法中,等效的 C# 代码完全相同。
您也可以简单地设置结构的SetCommonPOP字段;由于它是占用结构开头的uint,因此将具有相同的效果。