1. 如果函數只有傳入參數,比如:
C/C++ Code
Copy Code To Clipboard
- //C++中的輸出函數
- int__declspec(dllexport) test(constint N)
- {
- return N+10;
- }
對應的C#代碼為:
C# Code
Copy Code To Clipboard
- [DllImport("test.dll", EntryPoint = "#1")]
- publicstaticexternint test(int m);
- privatevoid button1_Click(object sender, EventArgs e)
- {
- textBox1.Text= test(10).ToString();
- }
2. 如果函數有傳出參數,比如:
C/C++ Code
Copy Code To Clipboard
- //C++
- void__declspec(dllexport) test(constint N, int& Z)
- {
- Z=N+10;
- }
對應的C#代碼:
C# Code
Copy Code To Clipboard
- [DllImport("test.dll", EntryPoint = "#1")]
- publicstaticexterndouble test(int m, refint n);
- privatevoid button1_Click(object sender, EventArgs e)
- {
- int N = 0;
- test1(10, ref N);
- textBox1.Text= N.ToString();
- }
3. 帶傳入數組:
C/C++ Code
Copy Code To Clipboard
- void__declspec(dllexport) test(constint N, constint n[], int& Z)
- {
- for (int i=0; i<N; i++)
- {
- Z+=n[i];
- }
- }
C#代碼:
C# Code
Copy Code To Clipboard
- [DllImport("test.dll", EntryPoint = "#1")]
- publicstaticexterndouble test(int N, int[] n, refint Z);
- privatevoid button1_Click(object sender, EventArgs e)
- {
- int N = 0;
- int[] n;
- n = newint[10];
- for (int i = 0; i < 10; i++)
- {
- n[i] = i;
- }
- test(n.Length, n, ref N);
- textBox1.Text= N.ToString();
- }
4. 帶傳出數組:
C++不能直接傳出數組,只傳出數組指針,
C/C++ Code
Copy Code To Clipboard
- void__declspec(dllexport) test(constint M, constint n[], int *N)
- {
- for (int i=0; i<M; i++)
- {
- N[i]=n[i]+10;
- }
- }
對應的C#代碼:
C# Code
Copy Code To Clipboard
- [DllImport("test.dll", EntryPoint = "#1")]
- publicstaticexternvoid test(int N, int[] n, [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Z);
- privatevoid button1_Click(object sender, EventArgs e)
- {
- int N = 1000;
- int[] n, Z;
- n = newint[N];Z = newint[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[] Z
在C#中數組是直接使用的,而在C++中返回的是數組的指針,這句用來轉化這兩種不同的類型.
關於MarshalAs的參數用法以及數組的Marshaling,可以參見這篇轉帖的文章: http://www.kycis.com/blog/read.php?21
