傳遞數組
傳遞定長數組很簡單,此處不述。下面的代碼實現變長數組的傳遞:
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#平台上就是比較簡單的事情了。