C#调用C++编写的DLL函数, 以及各种类型的参数传递--转载

1. 如果函数只有传入参数,比如:

01.//C++中的输出函数 
02.int __declspec(dllexport) test(const int N) 
03.{ 
04.return N+10; 
05.} 

 对应的C#代码为:

01.[DllImport("test.dll", EntryPoint = "#1")] 
02.public static extern int test(int m); 
03. 
04.private void button1_Click(object sender, EventArgs e) 
05.{ 
06.textBox1.Text= test(10).ToString(); 
07.} 

2. 如果函数有传出参数,比如:

01.//C++
02.void __declspec(dllexport) test(const int N, int& Z) 
03.{ 
04.Z=N+10; 
05.} 

对应的C#代码:

01.[DllImport("test.dll", EntryPoint = "#1")] 
02.public static extern double test(int m, ref int n); 
03. 
04.private void button1_Click(object sender, EventArgs e) 
05.{ 
06.int N = 0; 
07.test1(10, ref N); 
08.textBox1.Text= N.ToString(); 
09.} 

3. 带传入数组:

01.void __declspec(dllexport) test(const int N, const int n[], int& Z) 
02.{ 
03.for (int i=0; i<N; i++) 
04.{ 
05.Z+=n[i]; 
06.} 
07.} 

C#代码:

01.[DllImport("test.dll", EntryPoint = "#1")] 
02.public static extern double test(int N, int[] n, ref int Z); 
03. 
04.private void button1_Click(object sender, EventArgs e) 
05.{ 
06.int N = 0; 
07.int[] n; 
08.n = new int[10]; 
09.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++不能直接传出数组,只传出数组指针,

01.void __declspec(dllexport) test(const int M, const int n[], int *N) 
02.{ 
03.for (int i=0; i<M; i++) 
04.{ 
05.N[i]=n[i]+10; 
06.} 
07.} 

对应的C#代码:

01.[DllImport("test.dll", EntryPoint = "#1")] 
02.public static extern void test(int N, int[] n, [MarshalAs(UnmanagedType.LPArray,SizeParamIndex=1)] int[] Z); 
03. 
04.private void button1_Click(object sender, EventArgs e) 
05.{ 
06.int N = 1000; 
07.int[] n, Z; 
08.n = new int[N];Z = new int[N]; 
09.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++中返回的是数组的指针,这句用来转化这两种不同的类型.

posted on 2013-05-30 20:22  亲亲柚子  阅读(158)  评论(0编辑  收藏  举报

导航