C#調用C++編寫的DLL函數, 以及各種類型的參數傳遞 z


1. 如果函數只有傳入參數,比如:

C/C++ Code Copy Code To Clipboard
  1. //C++中的輸出函數
  2. int__declspec(dllexport) test(constint N)
  3. {
  4. return N+10;
  5. }

對應的C#代碼為:

C# Code Copy Code To Clipboard
  1. [DllImport("test.dll", EntryPoint = "#1")]
  2. publicstaticexternint test(int m);
  3.  
  4. privatevoid button1_Click(object sender, EventArgs e)
  5. {
  6. textBox1.Text= test(10).ToString();
  7. }

2. 如果函數有傳出參數,比如:

C/C++ Code Copy Code To Clipboard
  1. //C++
  2. void__declspec(dllexport) test(constint N, int& Z)
  3. {
  4. Z=N+10;
  5. }

對應的C#代碼:

C# Code Copy Code To Clipboard
  1. [DllImport("test.dll", EntryPoint = "#1")]
  2. publicstaticexterndouble test(int m, refint n);
  3.  
  4. privatevoid button1_Click(object sender, EventArgs e)
  5. {
  6. int N = 0;
  7. test1(10, ref N);
  8. textBox1.Text= N.ToString();
  9. }

3. 帶傳入數組:

C/C++ Code Copy Code To Clipboard
  1. void__declspec(dllexport) test(constint N, constint n[], int& Z)
  2. {
  3. for (int i=0; i<N; i++)
  4. {
  5. Z+=n[i];
  6. }
  7. }

C#代碼:

C# Code Copy Code To Clipboard
  1. [DllImport("test.dll", EntryPoint = "#1")]
  2. publicstaticexterndouble test(int N, int[] n, refint Z);
  3.  
  4. privatevoid button1_Click(object sender, EventArgs e)
  5. {
  6. int N = 0;
  7. int[] n;
  8. n = newint[10];
  9. for (int i = 0; i < 10; i++)
  10. {
  11. n[i] = i;
  12. }
  13. test(n.Length, n, ref N);
  14. textBox1.Text= N.ToString();
  15. }

4. 帶傳出數組:

C++不能直接傳出數組,只傳出數組指針,

C/C++ Code Copy Code To Clipboard
  1. void__declspec(dllexport) test(constint M, constint n[], int *N)
  2. {
  3. for (int i=0; i<M; i++)
  4. {
  5. N[i]=n[i]+10;
  6. }
  7. }

對應的C#代碼:

C# Code Copy Code To Clipboard
  1. [DllImport("test.dll", EntryPoint = "#1")]
  2. publicstaticexternvoid test(int N, int[] n, [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Z);
  3.  
  4. privatevoid button1_Click(object sender, EventArgs e)
  5. {
  6. int N = 1000;
  7. int[] n, Z;
  8. n = newint[N];Z = newint[N];
  9. for (int i = 0; i < N; i++)
  10. {
  11. n[i] = i;
  12. }
  13. test(n.Length, n, Z);
  14. for (int i=0; i<Z.Length; i++)
  15. {
  16. textBox1.AppendText(Z[i].ToString()+"n");
  17. }
  18. }

這里聲明函數入口時,注意這句 [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Z

在C#中數組是直接使用的,而在C++中返回的是數組的指針,這句用來轉化這兩種不同的類型.

關於MarshalAs的參數用法以及數組的Marshaling,可以參見這篇轉帖的文章: http://www.kycis.com/blog/read.php?21


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM