1. 若是函數只有傳入參數,好比:php
//C++中的輸出函數 int __declspec(dllexport) test(const int N) { return N+10; }
對應的C#代碼爲:數組
[DllImport("test.dll", EntryPoint = "#1")] public static extern int test(int m); private void button1_Click(object sender, EventArgs e) { textBox1.Text= test(10).ToString(); }
2. 若是函數有傳出參數,好比:函數
void __declspec(dllexport) test(const int N, int& Z) { Z=N+10; }
對應的C#代碼:spa
[DllImport("test.dll", EntryPoint = "#1")] public static extern double test(int m, ref int n); private void button1_Click(object sender, EventArgs e) { int N = 0; test1(10, ref N); textBox1.Text= N.ToString(); }
3. 帶傳入數組:指針
void __declspec(dllexport) test(const int N, const int n[], int& Z) { for (int i=0; i<N; i++) { Z+=n[i]; } }
C#代碼:code
[DllImport("test.dll", EntryPoint = "#1")] public static extern double test(int N, int[] n, ref int Z); private void button1_Click(object sender, EventArgs e) { int N = 0; int[] n; n = new int[10]; for (int i = 0; i < 10; i++) { n[i] = i; } test(n.Length, n, ref N); textBox1.Text= N.ToString(); }
4. 帶傳出數組:blog
C++不能直接傳出數組,只傳出數組指針,ip
void __declspec(dllexport) test(const int M, const int n[], int *N) { for (int i=0; i<M; i++) { N[i]=n[i]+10; } }
對應的C#代碼:ci
[DllImport("test.dll", EntryPoint = "#1")] public static extern void test(int N, int[] n, [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Z); private void button1_Click(object sender, EventArgs e) { int N = 1000; int[] n, Z; n = new int[N];Z = new int[N]; for (int i = 0; i < N; i++) { n[i] = i; } test(n.Length, n, Z); for (int i=0; i<Z.Length; i++) { textBox1.AppendText(Z[i].ToString()+"n"); } }
這裏聲明函數入口時,注意這句 [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Zget
在C#中數組是直接使用的,而在C++中返回的是數組的指針,這句用來轉化這兩種不一樣的類型.
關於MarshalAs的參數用法以及數組的Marshaling,能夠參見這篇轉帖的文章: http://www.kycis.com/blog/read.php?21
5. 傳出字符數組:
C++定義:
void __declspec(dllexport) test(int i, double &a, double &b, char t[5])
C#對應聲明:
[DllImport("dll.dll", EntryPoint = "test")] public static extern void test(int i, ref double a, ref double b, [Out, MarshalAs(UnmanagedType.LPArray)] char[] t); 。。。 char[] t = new char[5]; test(i, ref a, ref b, t);
字符數組的傳遞基本與4類似,只是mashalAs 時前面加上Out。