【问题标题】:how to retrieve values from pointer to array of ULONG in C#如何在 C# 中从指向 ULONG 数组的指针中检索值
【发布时间】:2015-05-19 09:58:35
【问题描述】:

C++ 结构:

typedef struct _denom 
    { 
     CHAR       cCurrencyID[3]; 
     int       ulAmount; 
     short     usCount; 
     LPULONG    lpulValues; //pointer to array of ULONGS 
     int      ulCashBox;        
    } DENOMINAT, * LPDENOMINAT; 

C# 中的结构:

[ StructLayout( LayoutKind.Sequential, 
CharSet=CharSet.Ansi, Pack=1 ) ] 
 public struct  DENOMINAT 
 { 
   [ MarshalAs( UnmanagedType.ByValArray, SizeConst=3 ) ] 
  public char[] cCurrencyID; 
  public int ulAmount; 
  public short usCount; 
  public IntPtr lpulValues; 
  public int ulCashBox;     
} 

lpulValues 是一个指向 ulongs 数组的指针,它的数组大小基于 usCount 例如:如果 uscount 为 5,那么在 C++ 中它将是 lpulValues = new ULONG[usCount];

我可以轻松地在 C++ 中获取数组值,这在 C# 中是不可能的。我不明白如何通过IntPtr 获取数组值。 提前致谢。

【问题讨论】:

    标签: c# c++ pointers marshalling intptr


    【解决方案1】:

    重要的事情

    在 Windows 中,在 C/C++ 中,sizeof(long) == sizeof(int)。所以sizeof(C-long) == sizeof(C#-int)。见https://stackoverflow.com/a/9689080/613130

    你应该可以做到:

    var denominat = new DENOMINAT();
    
    var uints = new uint[denominat.usCount];
    Marshal.Copy(denominat.lpulValues, (int[])(Array)uints, 0, uints.Length);
    

    请注意,我们有点作弊,将uint[] 转换为int[],但这是合法的,因为它们仅在符号上有所不同(请参阅https://stackoverflow.com/a/593799/613130

    我认为您不能使用 .NET PInvoke 封送处理程序自动完成。

    显示数组:

    for (int i = 0; i < uints.Length; i++)
    {
        Console.WriteLine(uints[i]);
    }
    

    【讨论】:

    • @TechBrkTru 查看添加的行
    • :我将如何显示 lpulvalues 的数组值,例如:如果 ulongs 长度为 5?在 C++ 中我可以将其显示为 lpulValues[0] ,lpulValue[1] ...等等在 C# 中怎么可能
    • 为什么不使用 (ulong[]) 而不是 (long[])
    • 强制转换是必要的,因为Marshal.Copy 没有ulong[] 的重载,但仅适用于long[],所以我不得不欺骗它使用long[] 重载输出ulong[] 数组。
    • @xanatos: 我在执行 for 循环时得到地址值。我需要访问存储在这些地址中的值
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多