a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 98|回复: 1

[程序员] 2012年软件水平考试程序员辅导笔记之C语言封送结构体数组

[复制链接]
发表于 2012-8-2 08:51:15 | 显示全部楼层 |阅读模式
在使用第三方的非托管API时,我们经常会遇到参数为指针或指针的指针这种情况, 8 h# h' G, n$ S3 e0 Q
  一般我们会用IntPtr指向我们需要传递的参数地址; , d; s% o  n0 x+ E7 ]
  但是当遇到这种一个导出函数时,我们如何正确的使用IntPtr呢,
7 p/ w) [5 |+ A( N/ K   extern “C” __declspec(dllexport) int GetClass(Class pClass[50]) ;
1 G( K0 M- Q: W3 n  由于这种情况也经常可能遇到,所以我制作了2个示例程序来演示下如何处理这种非托管函数的调用! 2 e$ N' L0 s0 o; a; C2 T
  首先创建一个C++ 的DLL 设置一个如上的导出函数 / v7 g# s5 ^: w$ ~& a' A( p6 ]$ {
   #include #include typedef struct Student { char name[20];int age;double scores[32];}Student;typedef struct Class { int number;Student students[126];}Class;extern “C” __declspec(dllexport) int GetClass(Class pClass[50])
6 }: X% Z; c7 P( w4 I3 U, v   { for(int i=0;i
回复

使用道具 举报

 楼主| 发表于 2012-8-2 08:51:16 | 显示全部楼层

2012年软件水平考试程序员辅导笔记之C语言封送结构体数组

  示例C语言封送结构体数组演示代码如下
" K! U6 M0 M; K- j" m   1 static void Main(string[] args)
2 n: D, ?( ~/ D% N   2 {
% o% C7 {! t3 p8 _2 g   3 int size = Marshal.SizeOf(typeof(Class)) * 50;
6 m* `* j5 o7 P& b4 r. |, \7 x  ]   4 byte[] bytes = new byte[size]; , Q% F4 ~* x! b& \; k
   5 IntPtr pBuff = Marshal.AllocHGlobal(size); : z$ I' j) \6 P6 l& d
   6 Class[] pClass = new Class[50];
) u% x' x' O4 I4 t- s; C   7 GetClass(pBuff); 0 c) f* Y" u# H' i- ~
   8 for (int i = 0; i < 50; i++) $ [, X  ]# _0 x- H- n
   9 { ' t! B: b) ^, g
   10 IntPtr pPonitor = new IntPtr(pBuff.ToInt64() + Marshal.SizeOf(typeof(Class)) * i);
' h! ?1 m9 `: x6 z   11 pClass = (Class)Marshal.PtrToStructure(pPonitor, typeof(Class)); ; y) j* C( j5 F) H" R1 [' r
   12 } 4 s2 x. Q: r- O' E
   13 Marshal.FreeHGlobal(pBuff); 6 U4 w" M6 \9 ^! b( L' y
   14 Console.ReadLine();    15 }有兴趣的不妨自己测试一下C语言封送结构体数组,看看输出结果是否正确!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-5-4 03:49 , Processed in 0.213254 second(s), 23 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表