传递数组
传递定长数组很简单
,此处不述
。下面的代码实现变长数组的传递:
C++代码:
int StaticElementNumber = 10;
extern "C" AFX_API_EXPORT bool GetArray(int ElementNumber, double *BaseAddress)
{
if (ElementNumber < StaticElementNumber)
{
return false;
}
for (int i = 0; i < StaticElementNumber; ++i)
{
BaseAddress[i] = 1 / ((double)i + 1);
}
return true;
}
extern "C" AFX_API_EXPORT int GetArrayElementNumber()
{
return StaticElementNumber;
}
C#代码:
[DllImport("MFCDll.dll")]
public static extern bool GetArray(int ElementNumber, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] double[] BaseAddress);
private void MenuItemFileGetArrayOnClicked(object sender, RoutedEventArgs e)
{
//Get array data.
int ElementNumber = GetArrayElementNumber();
double[] doubleArray = new double[ElementNumber];
GetArray(ElementNumber, doubleArray);
//Show the data.
mainGrid.Children.Clear();
ListBox listBox = new ListBox();
foreach (double number in doubleArray)
{
listBox.Items.Add(number);
}
mainGrid.Children.Add(listBox);
}
有了这三个功能
,一般来说C++代码复用到C#平台上就是比较简单的事情了
。