我在VC ++中的C ++项目中创建了一些函数,例如:
// Basically the power is an array
int read_power( int * power, int iByteNumToRead);
现在我需要通过编译DLL库中的C ++代码并使用链接到声明的C#函数来为C#项目中的这些函数创建C#等效/包装器。它最终会是这样的:
[DllImport("my_lib_dll.dll",CallingConvention = CallingConvention.Cdecl)]
unsafe public static extern int read_power( int * power, int iByteNumToRead);
public static int read_power_cs( int[] power, int iByteNumToRead )
{
if (power.Length < iByteNumToRead)
{
Console.WriteLine("Error: iByteNumToRead should be <= size of array[]");
return -1;
}
//Pinning the array
unsafe
{
fixed (int* ptr = power)
{
return read_power_cs( ptr, iByteNumToRead);
}
}
}
这里的问题是:在进入C ++函数之前是否需要固定数组?是否需要这样做?我知道我们这样做,以便垃圾编译器不会决定删除数组,但这是否需要?或者,我可以在没有包装器的情况下声明C#函数:
[DllImport("my_lib_dll.dll",CallingConvention = CallingConvention.Cdecl)]
public static extern int read_power( int[] power, int iByteNumToRead);
请注意,这已经过测试并且有效。我似乎无法理解是否需要固定阵列?我可以澄清一下,因为我是C#世界的新手。
由于