如何将 uint[] c# 传递给 c++ dll?

how to pass uint[] c# to c++ dll?

我正在开发一个与 C++ DLL 通信的 C# 程序。

提供的C++ DLL中的结构类型如下:

struct ST_TEST
{
    unsigned long* anIDs;
    unsigned long anIDCount;
};

我为匹配上述结构而创建的C#结构如下:

[StructLayout(LayoutKind.Sequential)]
public struct ST_TEST
{
    public IntPtr anIDs;
    public uint anIDCount;
}

在那之后,我想做的是设置 C# 结构的对象以将该结构从 C# 传递到 C++,如下所示:

uint[] IDs = { 12824874, 7865845, 45875792 };

ST_TEST stTest = new ST_TEST();
stTest.anIDCount = (uint)IDs.Length;

IntPtr buffer = Marshal.AllocHGlobal(IDs.Length);
try{
          Marshal.Copy(IDs, 0, buffer, IDs.Length);
          stTest.anIDs = buffer;
          //... call c++ dll
}
finally
{
          Marshal.FreeHGlobal(buffer);
}

如上执行时,Marshal.Copy()出现如下错误:

Can't convert from uint[] to int[]

如何将 uint[] 作为 unsigned long* 传递给 C++ DLL?

你不能使用 uint 因为元帅 class 没有那个类型的重载,因为它是 不符合 CLS。

但是,由于您要复制数组中的字节,因此 int 会起作用,因为它的大小正确, 并且 C++ 代码在接收到数组元素时仍会将其视为 uint

另请注意,使用Marshal.AllocHGlobal()时,必须指定字节数,而不是 数组元素的数量。

确保在 C++ 函数返回并且不再是之前不要调用 Marshal.FreeHGlobal() 使用数组指针。

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct ST_TEST
{
  public IntPtr anIDs;
  public int anIDCount;
 }
        
public class Program
{
  public static void Main()
  {
    try
    {
      Console.WriteLine("Hello World");
      int[] IDs = { 12824874, 7865845, 45875792 };
      ST_TEST stTest = new ST_TEST();
      stTest.anIDCount = IDs.Length;
      IntPtr buffer = Marshal.AllocHGlobal(IDs.Length * sizeof(int));
      Marshal.Copy(IDs, 0, buffer, IDs.Length);
      stTest.anIDs = buffer;
      // ... call native function
      // ...
    }
    finally
    {
      Marshal.FreeHGlobal(buffer);
    }
  }
}