WEB开发网
开发学院软件开发C语言 c#编程指南(十一) 平台调用P-INVOKE完全掌握, 指针... 阅读

c#编程指南(十一) 平台调用P-INVOKE完全掌握, 指针大全

 2010-09-30 22:46:10 来源:WEB开发网   
核心提示: c#:1[DllImport("TestDll")]2publicstaticexternIntPtrReadPoint2();3//#4IntPtrp10=ReadPoint2();5IntPtrp11=Marshal.ReadIntPtr(p10);6inttest10=

c#:

1     [DllImport("TestDll")]
2     public static extern IntPtr ReadPoint2();
3       //#########################
4       IntPtr p10 = ReadPoint2();
5       IntPtr p11 = Marshal.ReadIntPtr(p10);
6       int test10 = Marshal.ReadInt32(p11);
7       Console.WriteLine(test10);

第五:指针数组没有太直接的方法,因为C++所有指针都是4BYTE所以这里我是这么读的。

C++:

 1 static int test13 = 666;
 2 static int test14 = 777;
 3 static int * test15[3] = {0};
 4 int ** __stdcall ReadPointArray()
 5 {
 6   test15[0] = &test11;
 7   test15[1] = &test13;
 8   test15[2] = &test14;
 9   return test15;
10 }

C#:

1     [DllImport("TestDll")]
2     public static extern IntPtr ReadPointArray();      
3 //#########################
4       IntPtr p12 = ReadPointArray();
5       int test11 = p12.ToInt32();
6       Console.WriteLine(Marshal.ReadInt32(Marshal.ReadIntPtr(p12)));
7       Console.WriteLine(Marshal.ReadInt32(Marshal.ReadIntPtr(new IntPtr(test11 + 0))));
8       Console.WriteLine(Marshal.ReadInt32(Marshal.ReadIntPtr(new IntPtr(test11 + 4))));
9       Console.WriteLine(Marshal.ReadInt32(Marshal.ReadIntPtr(new IntPtr(test11 + 8))));

最后: 结构体的指针,用C#建立对应C++的结构体,并使用   [StructLayout(LayoutKind.Sequential)]属性,

使用Marshal.PtrToStructure()读取。

c++:

 1 struct Test
 2 {
 3   int test;
 4 };
 5 
 6 static Test test16;
 7 Test * __stdcall ReadStruct()
 8 {
 9   test16.test = 1234;
10   return &test16;
11 }

c#:

 1     [StructLayout(LayoutKind.Sequential)]
 2     public struct Test
 3     {
 4       public int test;
 5     }
 6 
 7     [DllImport("TestDll")]
 8     public static extern IntPtr ReadStruct();
 9       //#########################
10 
11       IntPtr p13 = ReadStruct();
12       Test test13 = (Test)Marshal.PtrToStructure(p13,typeof(Test));
13       Console.WriteLine(test13.test);

上一页  1 2 3 

Tags:编程 指南 十一

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接