我正在尝试在C#应用程序中使用C ++代码。创建以下结构:
System.Runtime.InteropServices.StructLayout(
System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct My_FSet
{
public int Num;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 100)]
public uint[] Freqs;
}
我想在我的代码中像数组一样使用它,比如
My_FSet FSet = new My_FSet();
FSet.Freqs[0] = 1000;
FSet.Freqs[1] = 2500;
FSet.Freqs[3] = 3200;
但是我收到了一个错误:
未处理的类型' System.NullReferenceException'发生在MyApp.exe
中附加信息:未将对象引用设置为对象的实例。
似乎数组没有正确初始化,但我不能在结构中这样做,所以我该如何解决这个问题呢?
答案 0 :(得分:1)
问题是array is never instantiated, hence the NullReferenceException
。由于结构与类略有不同,因此您必须提供有关对象创建的信息,而不是稍后对其进行分配。
像这样:
public struct My_FSet
{
public readonly int Num;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 100)]
public readonly uint[] Freqs;
public My_FSet(int num, uint[] freqs)
{
this.Num = num;
this.Freqs = freqs;
}
}
然后你可以在构造函数中提供数组:
My_FSet f = new My_FSet(1, new uint[] { 1, 2, 3 });