C#中调用Windows API的要点 .

介绍

  API(Application Programming Interface),我想大家不会陌生,它是我们Windows编程的常客,虽然基于.Net平台的C#有了强大的类库,但是,我们还是不能否认API在Windows编程中的重要性。大多数的编程语言都支持API编程,而.Net平台中的MFC(Microsoft Foundation Class Library)构架本身就封装了大部分的API。

  做为程序员,我们需要了解API从字面上了解便是编程接口,因此,做为开发者,需要了解的只是API的使用方法。

  API根据操作系统、处理器及功能性的不同而拥有很多不同的类型。   操作系统特用的API:

  每种操作系统都有许多通用的API以及一些特用的API,这些特用的API只能在当前操作系统中执行。

  例如:

  Windows NT 支持 MS-DOS, Win16, Win32, POSIX (Portable Operating System Interface), OS/2 console API; 而 Windows 95 支持 MS-DOS, Win16 以及 Win32 APIs.

  Win16 & Win32 API:

  Win16是为十六位处理器开发的,早期的操作系统均支持。

  Win32则是为32位处理器开发。它可移植性强,被大部分的处理器所支持。

  Win32 API在库名后有一个”32”后缀。比如KERNEL32,USER32等。

  所有API在下面3个库中得以运行:

  Kernel
  User
  GDI


  1. KERNEL

  他的库名为 KERNEL32.DLL, 他主要用于产生与操作系统之间的关联:

  程序加载
  上下文选择.
  文件输入输出.
  内存管理.
  例如: GlobalMemoryStatus 函数就包括当前物理内存及虚拟内存的使用信息。

  2. USER

  这个类库在Win32中名叫 USER32.DLL。

  它允许管理全部的用户接口,比如:

  窗口
  菜单
  对话框
  图标等.,
  例如: DrawIcon 函数将在指定的设备关联上“画”出图标或者鼠标。

  3. GDI (Graphical Device Interface)

  它在Win32中的库名为:GDI32.dll,它是图形输出库。使用GDI Windows“画”出窗口、菜单以及对话框等:

  它能创建图形输出.
  它也能保存图形文件.
  例如: CreateBitmap 函数就能通过指定的长、宽、颜色创建一个位图。

 


  C# 中操作API:

  作为初学者来说,在C#中使用API确是一件令人头疼的问题。在使用API之间你必须知道如何在C#中使用结构、类型转换、安全/不安全代码,可控/不可控代码等许多知识。

  一切从简单开始,复杂的大家一时不能接受。我们就从实现一个简单的MessageBox开始。首先打开VS.Net ,创建一个新的C#工程,并添加一个Button按钮。当这个按钮被点击,则显示一个MessageBox对话框。

  即然我们需要引用外来库,所以必须导入一个Namespace:

 

  using System.Runtime.InteropServices;

 


  接着添加下面的代码来声明一个API:

 

  [DllImport("User32.dll")]

  public static extern int MessageBox(int h, string m, string c, int type);

 


  此处DllImport属性被用来从不可控代码中调用一方法。”User32.dll”则设定了类库名。DllImport属性指定dll的位置,这个dll中包括调用的外部方法。Static修饰符则声明一个静态元素,而这个元素属于类型本身而不是上面指定的对象。extern则表示这个方法将在工程外部执行,使用DllImport导入的方法必须使用extern修饰符。

  MessageBox 则是函数名,拥有4个参数,其返回值为数字。

  大多数的API都能传递并返回值。

  添中Click点击事件代码:

 

  protected void button1_Click(object sender, System.EventArgs e)

  {

      MessageBox (0,"API Message Box","API Demo",0);

  }

 



  编译并运行这个程序,当你点击按钮后,你将会看到对话框,这便是你使用的API函数。

  使用结构体

  操作带有结构体的API比使用简单的API要复杂的多。但是一旦你掌握了API的过程,那个整个API世界将在你的掌握之中。

  下面的例子中我们将使用GetSystemInfo API 来获取整个系统的信息。

  第一步还是打开C#建立一个Form工程,同样的添中一个Button按钮,在代码窗中输入下面的代码,导入Namespace:

 

  using System.Runtime.InteropServices;

 


  声明一个结构体,它将做为GetSystemInfo的一个参数:

 



  [StructLayout(LayoutKind.Sequential)]

  public struct SYSTEM_INFO {

      public uint dwOemId;

      public uint dwPageSize;

      public uint lpMinimumApplicationAddress;

      public uint lpMaximumApplicationAddress;

      public uint dwActiveProcessorMask;

      public uint dwNumberOfProcessors;

      public uint dwProcessorType;

      public uint dwAllocationGranularity;

      public uint dwProcessorLevel;

      public uint dwProcessorRevision;

  }

 


  声明API函数:

 



  [DllImport("kernel32")]

  static extern void GetSystemInfo(ref SYSTEM_INFO pSI);

 



  添加下面的代码至按钮的点击事件处理中:

  首先创建一个SYSTEM_INFO结构体,并将其传递给GetSystemInfo函数。

 



  protected void button1_Click (object sender, System.EventArgs e)

  {

      try

      {

          SYSTEM_INFO pSI = new SYSTEM_INFO();

          GetSystemInfo(ref pSI);

          //

          //

          //

 


  一旦你接收到返回的结构体,那么就可以以返回的参数来执行操作了。

 



  e.g.listBox1.InsertItem (0,pSI.dwActiveProcessorMask.ToString());:

          //

          //

          //

     }

     catch(Exception er)

     {

          MessageBox.Show (er.Message);

     }

  }

 

 

 

 

 

  1 调用API全部代码   
  2   
  3   //Created By Ajit Mungale    
  4   
  5   //程序补充 飞刀    
  6   
  7   namespace UsingAPI   
  8   
  9   {   
 10   
 11   using System;   
 12   
 13   using System.Drawing;   
 14   
 15   using System.Collections;   
 16   
 17   using System.ComponentModel;   
 18   
 19   using System.WinForms;   
 20   
 21   using System.Data;   
 22   
 23   using System.Runtime.InteropServices;   
 24   
 25   //Struct 收集系统信息    
 26   
 27   [StructLayout(LayoutKind.Sequential)]   
 28   
 29   public struct SYSTEM_INFO {   
 30   
 31         public uint dwOemId;   
 32   
 33         public uint dwPageSize;   
 34   
 35         public uint lpMinimumApplicationAddress;   
 36   
 37         public uint lpMaximumApplicationAddress;   
 38   
 39         public uint dwActiveProcessorMask;   
 40   
 41         public uint dwNumberOfProcessors;   
 42   
 43         public uint dwProcessorType;   
 44   
 45         public uint dwAllocationGranularity;   
 46   
 47         public uint dwProcessorLevel;   
 48   
 49         public uint dwProcessorRevision;   
 50   
 51     }   
 52   
 53   //struct 收集内存情况    
 54   
 55   [StructLayout(LayoutKind.Sequential)]   
 56   
 57   public struct MEMORYSTATUS   
 58   
 59   {   
 60   
 61        public uint dwLength;   
 62   
 63        public uint dwMemoryLoad;   
 64   
 65        public uint dwTotalPhys;   
 66   
 67        public uint dwAvailPhys;   
 68   
 69        public uint dwTotalPageFile;   
 70   
 71        public uint dwAvailPageFile;   
 72   
 73        public uint dwTotalVirtual;   
 74   
 75        public uint dwAvailVirtual;   
 76   
 77   }   
 78   
 79   public class Form1 : System.WinForms.Form   
 80   
 81   {   
 82   
 83     private System.ComponentModel.Container components;   
 84   
 85     private System.WinForms.MenuItem menuAbout;   
 86   
 87     private System.WinForms.MainMenu mainMenu1;   
 88   
 89     private System.WinForms.ListBox listBox1;   
 90   
 91     private System.WinForms.Button button1;   
 92   
 93   //获取系统信息    
 94   
 95     [DllImport("kernel32")]   
 96   
 97     static extern void GetSystemInfo(ref SYSTEM_INFO pSI);   
 98   
 99     //获取内存信息    
100   
101     [DllImport("kernel32")]   
102   
103     static extern void GlobalMemoryStatus(ref MEMORYSTATUS buf);   
104   
105     //处理器类型    
106   
107     public const int PROCESSOR_INTEL_386 = 386;   
108   
109     public const int PROCESSOR_INTEL_486 = 486;   
110   
111     public const int PROCESSOR_INTEL_PENTIUM = 586;   
112   
113     public const int PROCESSOR_MIPS_R4000 = 4000;   
114   
115     public const int PROCESSOR_ALPHA_21064 = 21064;   
116   
117     public Form1()   
118   
119     {   
120   
121       InitializeComponent();   
122   
123     }   
124   
125     public override void Dispose()   
126   
127     {   
128   
129       base.Dispose();   
130   
131       components.Dispose();   
132   
133     }   
134   
135     private void InitializeComponent()   
136   
137      {   
138   
139        this.components = new System.ComponentModel.Container ();   
140   
141        this.mainMenu1 = new System.WinForms.MainMenu ();   
142   
143        this.button1 = new System.WinForms.Button ();   
144   
145        this.listBox1 = new System.WinForms.ListBox ();   
146   
147        this.menuAbout = new System.WinForms.MenuItem ();   
148   
149        mainMenu1.MenuItems.All = new System.WinForms.MenuItem[1] {this.menuAbout};   
150   
151        button1.Location = new System.Drawing.Point (148, 168);   
152   
153        button1.Size = new System.Drawing.Size (112, 32);   
154   
155        button1.TabIndex = 0;   
156   
157        button1.Text = "&Get Info";   
158   
159        button1.Click += new System.EventHandler (this.button1_Click);   
160   
161        listBox1.Location = new System.Drawing.Point (20, 8);   
162   
163        listBox1.Size = new System.Drawing.Size (368, 147);   
164   
165        listBox1.TabIndex = 1;   
166   
167        menuAbout.Text = "&About";   
168   
169        menuAbout.Index = 0;   
170   
171        menuAbout.Click += new System.EventHandler (this.menuAbout_Click);   
172   
173        this.Text = "System Information - Using API";   
174   
175        this.MaximizeBox = false;   
176   
177        this.AutoScaleBaseSize = new System.Drawing.Size (5, 13);   
178   
179        this.MinimizeBox = false;   
180   
181        this.Menu = this.mainMenu1;   
182   
183        this.ClientSize = new System.Drawing.Size (408, 213);   
184   
185        this.Controls.Add (this.listBox1);   
186   
187        this.Controls.Add (this.button1);   
188   
189     }   
190   
191     protected void menuAbout_Click (object sender, System.EventArgs e)   
192   
193     {   
194   
195        Form abt=new about() ;   
196   
197        abt.ShowDialog();   
198   
199     }   
200   
201     protected void button1_Click (object sender, System.EventArgs e)   
202   
203     {   
204   
205        try   
206   
207        {   
208   
209           SYSTEM_INFO pSI = new SYSTEM_INFO();   
210   
211           GetSystemInfo(ref pSI);   
212   
213           string CPUType;   
214   
215           switch (pSI.dwProcessorType)   
216   
217           {   
218   
219             case PROCESSOR_INTEL_386 :   
220   
221                CPUType= "Intel 386";   
222   
223                break;   
224   
225             case PROCESSOR_INTEL_486 :   
226   
227                CPUType = "Intel 486" ;   
228   
229               break;   
230   
231             case PROCESSOR_INTEL_PENTIUM :   
232   
233               CPUType = "Intel Pentium";   
234   
235               break;   
236   
237             case PROCESSOR_MIPS_R4000 :   
238   
239               CPUType = "MIPS R4000";   
240   
241               break;   
242   
243             case PROCESSOR_ALPHA_21064 :   
244   
245               CPUType = "DEC Alpha 21064";   
246   
247               break;   
248   
249             default :   
250   
251               CPUType = "(unknown)";   
252   
253          }   
254   
255          listBox1.InsertItem (0,"Active Processor Mask :"+pSI.dwActiveProcessorMask.ToString());   
256   
257          listBox1.InsertItem (1,"Allocation Granularity :"+pSI.dwAllocationGranularity.ToString());   
258   
259          listBox1.InsertItem (2,"Number Of Processors :"+pSI.dwNumberOfProcessors.ToString());   
260   
261          listBox1.InsertItem (3,"OEM ID :"+pSI.dwOemId.ToString());   
262   
263          listBox1.InsertItem (4,"Page Size:"+pSI.dwPageSize.ToString());   
264   
265          listBox1.InsertItem (5,"Processor Level Value:"+pSI.dwProcessorLevel.ToString());   
266   
267          listBox1.InsertItem (6,"Processor Revision:"+ pSI.dwProcessorRevision.ToString());   
268   
269          listBox1.InsertItem (7,"CPU type:"+CPUType);   
270   
271          listBox1.InsertItem (8,"Maximum Application Address: "+pSI.lpMaximumApplicationAddress.ToString());   
272   
273          listBox1.InsertItem (9,"Minimum Application Address:" +pSI.lpMinimumApplicationAddress.ToString());   
274   
275          /************** 从 GlobalMemoryStatus 获取返回值****************/   
276   
277          MEMORYSTATUS memSt = new MEMORYSTATUS ();   
278          GlobalMemoryStatus (ref memSt);  
279   
280          listBox1.InsertItem(10,"Available Page File :"+ (memSt.dwAvailPageFile/1024).ToString ());   
281   
282          listBox1.InsertItem(11,"Available Physical Memory : " + (memSt.dwAvailPhys/1024).ToString());   
283   
284          listBox1.InsertItem(12,"Available Virtual Memory:" + (memSt.dwAvailVirtual/1024).ToString ());   
285   
286          listBox1.InsertItem(13,"Size of structur :" + memSt.dwLength.ToString());   
287   
288          listBox1.InsertItem(14,"Memory In Use :"+ memSt.dwMemoryLoad.ToString());   
289   
290          listBox1.InsertItem(15,"Total Page Size :"+ (memSt.dwTotalPageFile/1024).ToString ());   
291   
292          listBox1.InsertItem(16,"Total Physical Memory :" + (memSt.dwTotalPhys/1024).ToString());   
293   
294          listBox1.InsertItem(17,"Total Virtual Memory :" + (memSt.dwTotalVirtual/1024).ToString ());   
295   
296        }   
297   
298        catch(Exception er)   
299   
300        {   
301   
302          MessageBox.Show (er.Message);   
303   
304        }   
305   
306     }   
307   
308     public static void Main(string[] args)   
309   
310     {   
311   
312       try   
313   
314        {   
315   
316           Application.Run(new Form1());   
317   
318        }   
319   
320        catch(Exception er)   
321   
322        {   
323   
324           MessageBox.Show (er.Message );   
325   
326        }   
327   
328    }   
329   
330   }   
331   
332 }   
333 调用API全部代码 
334 
335   //Created By Ajit Mungale 
336 
337   //程序补充 飞刀 
338 
339   namespace UsingAPI 
340 
341   { 
342 
343   using System; 
344 
345   using System.Drawing; 
346 
347   using System.Collections; 
348 
349   using System.ComponentModel; 
350 
351   using System.WinForms; 
352 
353   using System.Data; 
354 
355   using System.Runtime.InteropServices; 
356 
357   //Struct 收集系统信息 
358 
359   [StructLayout(LayoutKind.Sequential)] 
360 
361   public struct SYSTEM_INFO { 
362 
363         public uint dwOemId; 
364 
365         public uint dwPageSize; 
366 
367         public uint lpMinimumApplicationAddress; 
368 
369         public uint lpMaximumApplicationAddress; 
370 
371         public uint dwActiveProcessorMask; 
372 
373         public uint dwNumberOfProcessors; 
374 
375         public uint dwProcessorType; 
376 
377         public uint dwAllocationGranularity; 
378 
379         public uint dwProcessorLevel; 
380 
381         public uint dwProcessorRevision; 
382 
383     } 
384 
385   //struct 收集内存情况 
386 
387   [StructLayout(LayoutKind.Sequential)] 
388 
389   public struct MEMORYSTATUS 
390 
391   { 
392 
393        public uint dwLength; 
394 
395        public uint dwMemoryLoad; 
396 
397        public uint dwTotalPhys; 
398 
399        public uint dwAvailPhys; 
400 
401        public uint dwTotalPageFile; 
402 
403        public uint dwAvailPageFile; 
404 
405        public uint dwTotalVirtual; 
406 
407        public uint dwAvailVirtual; 
408 
409   } 
410 
411   public class Form1 : System.WinForms.Form 
412 
413   { 
414 
415     private System.ComponentModel.Container components; 
416 
417     private System.WinForms.MenuItem menuAbout; 
418 
419     private System.WinForms.MainMenu mainMenu1; 
420 
421     private System.WinForms.ListBox listBox1; 
422 
423     private System.WinForms.Button button1; 
424 
425   //获取系统信息 
426 
427     [DllImport("kernel32")] 
428 
429     static extern void GetSystemInfo(ref SYSTEM_INFO pSI); 
430 
431     //获取内存信息 
432 
433     [DllImport("kernel32")] 
434 
435     static extern void GlobalMemoryStatus(ref MEMORYSTATUS buf); 
436 
437     //处理器类型 
438 
439     public const int PROCESSOR_INTEL_386 = 386; 
440 
441     public const int PROCESSOR_INTEL_486 = 486; 
442 
443     public const int PROCESSOR_INTEL_PENTIUM = 586; 
444 
445     public const int PROCESSOR_MIPS_R4000 = 4000; 
446 
447     public const int PROCESSOR_ALPHA_21064 = 21064; 
448 
449     public Form1() 
450 
451     { 
452 
453       InitializeComponent(); 
454 
455     } 
456 
457     public override void Dispose() 
458 
459     { 
460 
461       base.Dispose(); 
462 
463       components.Dispose(); 
464 
465     } 
466 
467     private void InitializeComponent() 
468 
469      { 
470 
471        this.components = new System.ComponentModel.Container (); 
472 
473        this.mainMenu1 = new System.WinForms.MainMenu (); 
474 
475        this.button1 = new System.WinForms.Button (); 
476 
477        this.listBox1 = new System.WinForms.ListBox (); 
478 
479        this.menuAbout = new System.WinForms.MenuItem (); 
480 
481        mainMenu1.MenuItems.All = new System.WinForms.MenuItem[1] {this.menuAbout}; 
482 
483        button1.Location = new System.Drawing.Point (148, 168); 
484 
485        button1.Size = new System.Drawing.Size (112, 32); 
486 
487        button1.TabIndex = 0; 
488 
489        button1.Text = "&Get Info"; 
490 
491        button1.Click += new System.EventHandler (this.button1_Click); 
492 
493        listBox1.Location = new System.Drawing.Point (20, 8); 
494 
495        listBox1.Size = new System.Drawing.Size (368, 147); 
496 
497        listBox1.TabIndex = 1; 
498 
499        menuAbout.Text = "&About"; 
500 
501        menuAbout.Index = 0; 
502 
503        menuAbout.Click += new System.EventHandler (this.menuAbout_Click); 
504 
505        this.Text = "System Information - Using API"; 
506 
507        this.MaximizeBox = false; 
508 
509        this.AutoScaleBaseSize = new System.Drawing.Size (5, 13); 
510 
511        this.MinimizeBox = false; 
512 
513        this.Menu = this.mainMenu1; 
514 
515        this.ClientSize = new System.Drawing.Size (408, 213); 
516 
517        this.Controls.Add (this.listBox1); 
518 
519        this.Controls.Add (this.button1); 
520 
521     } 
522 
523     protected void menuAbout_Click (object sender, System.EventArgs e) 
524 
525     { 
526 
527        Form abt=new about() ; 
528 
529        abt.ShowDialog(); 
530 
531     } 
532 
533     protected void button1_Click (object sender, System.EventArgs e) 
534 
535     { 
536 
537        try 
538 
539        { 
540 
541           SYSTEM_INFO pSI = new SYSTEM_INFO(); 
542 
543           GetSystemInfo(ref pSI); 
544 
545           string CPUType; 
546 
547           switch (pSI.dwProcessorType) 
548 
549           { 
550 
551             case PROCESSOR_INTEL_386 : 
552 
553                CPUType= "Intel 386"; 
554 
555                break; 
556 
557             case PROCESSOR_INTEL_486 : 
558 
559                CPUType = "Intel 486" ; 
560 
561               break; 
562 
563             case PROCESSOR_INTEL_PENTIUM : 
564 
565               CPUType = "Intel Pentium"; 
566 
567               break; 
568 
569             case PROCESSOR_MIPS_R4000 : 
570 
571               CPUType = "MIPS R4000"; 
572 
573               break; 
574 
575             case PROCESSOR_ALPHA_21064 : 
576 
577               CPUType = "DEC Alpha 21064"; 
578 
579               break; 
580 
581             default : 
582 
583               CPUType = "(unknown)"; 
584 
585          } 
586 
587          listBox1.InsertItem (0,"Active Processor Mask :"+pSI.dwActiveProcessorMask.ToString()); 
588 
589          listBox1.InsertItem (1,"Allocation Granularity :"+pSI.dwAllocationGranularity.ToString()); 
590 
591          listBox1.InsertItem (2,"Number Of Processors :"+pSI.dwNumberOfProcessors.ToString()); 
592 
593          listBox1.InsertItem (3,"OEM ID :"+pSI.dwOemId.ToString()); 
594 
595          listBox1.InsertItem (4,"Page Size:"+pSI.dwPageSize.ToString()); 
596 
597          listBox1.InsertItem (5,"Processor Level Value:"+pSI.dwProcessorLevel.ToString()); 
598 
599          listBox1.InsertItem (6,"Processor Revision:"+ pSI.dwProcessorRevision.ToString()); 
600 
601          listBox1.InsertItem (7,"CPU type:"+CPUType); 
602 
603          listBox1.InsertItem (8,"Maximum Application Address: "+pSI.lpMaximumApplicationAddress.ToString()); 
604 
605          listBox1.InsertItem (9,"Minimum Application Address:" +pSI.lpMinimumApplicationAddress.ToString()); 
606 
607          /************** 从 GlobalMemoryStatus 获取返回值****************/ 
608 
609          MEMORYSTATUS memSt = new MEMORYSTATUS (); 
610          GlobalMemoryStatus (ref memSt);
611 
612          listBox1.InsertItem(10,"Available Page File :"+ (memSt.dwAvailPageFile/1024).ToString ()); 
613 
614          listBox1.InsertItem(11,"Available Physical Memory : " + (memSt.dwAvailPhys/1024).ToString()); 
615 
616          listBox1.InsertItem(12,"Available Virtual Memory:" + (memSt.dwAvailVirtual/1024).ToString ()); 
617 
618          listBox1.InsertItem(13,"Size of structur :" + memSt.dwLength.ToString()); 
619 
620          listBox1.InsertItem(14,"Memory In Use :"+ memSt.dwMemoryLoad.ToString()); 
621 
622          listBox1.InsertItem(15,"Total Page Size :"+ (memSt.dwTotalPageFile/1024).ToString ()); 
623 
624          listBox1.InsertItem(16,"Total Physical Memory :" + (memSt.dwTotalPhys/1024).ToString()); 
625 
626          listBox1.InsertItem(17,"Total Virtual Memory :" + (memSt.dwTotalVirtual/1024).ToString ()); 
627 
628        } 
629 
630        catch(Exception er) 
631 
632        { 
633 
634          MessageBox.Show (er.Message); 
635 
636        } 
637 
638     } 
639 
640     public static void Main(string[] args) 
641 
642     { 
643 
644       try 
645 
646        { 
647 
648           Application.Run(new Form1()); 
649 
650        } 
651 
652        catch(Exception er) 
653 
654        { 
655 
656           MessageBox.Show (er.Message ); 
657 
658        } 
659 
660    } 
661 
662   } 
663 
664 } 
665 
666 
667  

 

 

 

C#中调用Windows   API的要点    
  日期:2003年12月11日   作者:佚名   人气:586   查看:[大字体   中字体   小字体]      
     
  在.Net   Framework   SDK文档中,关于调用Windows   API的指示比较零散,并且其中稍全面一点的是针对Visual   Basic   .net讲述的。本文将C#中调用API的要点汇集如下,希望给未在C#中使用过API的朋友一点帮助。另外如果安装了Visual   Studio   .net的话,在C:/Program   Files/Microsoft   Visual   Studio   .NET/FrameworkSDK/Samples/Technologies/Interop/PlatformInvoke/WinAPIs/CS目录下有大量的调用API的例子。  
  一、调用格式  
  using   System.Runtime.InteropServices;   //引用此名称空间,简化后面的代码  
  ...  
  //使用DllImportAttribute特性来引入api函数,注意声明的是空方法,即方法体为空。  
  [DllImport("user32.dll")]  
  public   static   extern   ReturnType   FunctionName(type   arg1,type   arg2,...);  
  //调用时与调用其他方法并无区别  
   
  可以使用字段进一步说明特性,用逗号隔开,如:  
  [   DllImport(   "kernel32",   EntryPoint="GetVersionEx"   )]    
  DllImportAttribute特性的公共字段如下:  
  1、CallingConvention   指示向非托管实现传递方法参数时所用的   CallingConvention   值。    
      CallingConvention.Cdecl   :   调用方清理堆栈。它使您能够调用具有   varargs   的函数。  
      CallingConvention.StdCall   :   被调用方清理堆栈。它是从托管代码调用非托管函数的默认约定。  
  2、CharSet   控制调用函数的名称版本及指示如何向方法封送   String   参数。  
      此字段被设置为   CharSet   值之一。如果   CharSet   字段设置为   Unicode,则所有字符串参数在传递到非托管实现之前都转换成   Unicode   字符。这还导致向   DLL   EntryPoint   的名称中追加字母“W”。如果此字段设置为   Ansi,则字符串将转换成   ANSI   字符串,同时向   DLL   EntryPoint   的名称中追加字母“A”。大多数   Win32   API   使用这种追加“W”或“A”的约定。如果   CharSet   设置为   Auto,则这种转换就是与平台有关的(在   Windows   NT   上为   Unicode,在   Windows   98   上为   Ansi)。CharSet   的默认值为   Ansi。CharSet   字段也用于确定将从指定的   DLL   导入哪个版本的函数。CharSet.Ansi   和   CharSet.Unicode   的名称匹配规则大不相同。对于   Ansi   来说,如果将   EntryPoint   设置为“MyMethod”且它存在的话,则返回“MyMethod”。如果   DLL   中没有“MyMethod”,但存在“MyMethodA”,则返回“MyMethodA”。对于   Unicode   来说则正好相反。如果将   EntryPoint   设置为“MyMethod”且它存在的话,则返回“MyMethodW”。如果   DLL   中不存在“MyMethodW”,但存在“MyMethod”,则返回“MyMethod”。如果使用的是   Auto,则匹配规则与平台有关(在   Windows   NT   上为   Unicode,在   Windows   98   上为   Ansi)。如果   ExactSpelling   设置为   true,则只有当   DLL   中存在“MyMethod”时才返回“MyMethod”。  
   
  3、EntryPoint   指示要调用的   DLL   入口点的名称或序号。    
      如果你的方法名不想与api函数同名的话,一定要指定此参数,例如:  
  [DllImport("user32.dll",CharSet="CharSet.Auto",EntryPoint="MessageBox")]  
  public   static   extern   int   MsgBox(IntPtr   hWnd,string   txt,string   caption,   int   type);  
   
  4、ExactSpelling   指示是否应修改非托管   DLL   中的入口点的名称,以与   CharSet   字段中指定的   CharSet   值相对应。如果为   true,则当   DllImportAttribute.CharSet   字段设置为   CharSet   的   Ansi   值时,向方法名称中追加字母   A,当   DllImportAttribute.CharSet   字段设置为   CharSet   的   Unicode   值时,向方法的名称中追加字母   W。此字段的默认值是   false。    
  5、PreserveSig   指示托管方法签名不应转换成返回   HRESULT、并且可能有一个对应于返回值的附加   [out,   retval]   参数的非托管签名。    
  6、SetLastError   指示被调用方在从属性化方法返回之前将调用   Win32   API   SetLastError。   true   指示调用方将调用   SetLastError,默认为   false。运行时封送拆收器将调用   GetLastError   并缓存返回的值,以防其被其他   API   调用重写。用户可通过调用   GetLastWin32Error   来检索错误代码。  
   
  二、参数类型:  
  1、数值型直接用对应的就可。(DWORD   ->   int   ,   WORD   ->   Int16)  
  2、API中字符串指针类型   ->   .net中string  
  3、API中句柄   (dWord)     ->   .net中IntPtr  
  4、API中结构       ->   .net中结构或者类。注意这种情况下,要先用StructLayout特性限定声明结构或类  
  公共语言运行库利用StructLayoutAttribute控制类或结构的数据字段在托管内存中的物理布局,即类或结构需要按某种方式排列。如果要将类传递给需要指定布局的非托管代码,则显式控制类布局是重要的。它的构造函数中用LayoutKind值初始化   StructLayoutAttribute   类的新实例。   LayoutKind.Sequential   用于强制将成员按其出现的顺序进行顺序布局。  
  LayoutKind.Explicit   用于控制每个数据成员的精确位置。利用   Explicit,   每个成员必须使用   FieldOffsetAttribute   指示此字段在类型中的位置。如:  
  [StructLayout(LayoutKind.Explicit,   Size=16,   CharSet=CharSet.Ansi)]  
  public   class   MySystemTime    
  {  
          [FieldOffset(0)]public   ushort   wYear;    
          [FieldOffset(2)]public   ushort   wMonth;  
          [FieldOffset(4)]public   ushort   wDayOfWeek;    
          [FieldOffset(6)]public   ushort   wDay;    
          [FieldOffset(8)]public   ushort   wHour;    
          [FieldOffset(10)]public   ushort   wMinute;    
          [FieldOffset(12)]public   ushort   wSecond;    
          [FieldOffset(14)]public   ushort   wMilliseconds;    
  }  
  下面是针对API中OSVERSIONINFO结构,在.net中定义对应类或结构的例子:  
  /**********************************************  
  *   API中定义原结构声明  
  *   OSVERSIONINFOA   STRUCT  
  *     dwOSVersionInfoSize       DWORD             ?  
  *     dwMajorVersion                 DWORD             ?  
  *     dwMinorVersion                 DWORD             ?  
  *     dwBuildNumber                   DWORD             ?  
  *     dwPlatformId                     DWORD             ?  
  *     szCSDVersion                     BYTE   128   dup   (?)  
  *   OSVERSIONINFOA   ENDS  
  *  
  *   OSVERSIONINFO     equ     <OSVERSIONINFOA>  
  *********************************************/  
   
  //.net中声明为类  
  [   StructLayout(   LayoutKind.Sequential   )]        
  public   class   OSVersionInfo    
  {        
          public   int   OSVersionInfoSize;  
          public   int   majorVersion;    
          public   int   minorVersion;  
          public   int   buildNumber;  
          public   int   platformId;  
   
          [   MarshalAs(   UnmanagedType.ByValTStr,   SizeConst=128   )]          
          public   String   versionString;  
  }  
  //或者  
  //.net中声明为结构  
  [   StructLayout(   LayoutKind.Sequential   )]      
  public   struct   OSVersionInfo2    
  {  
          public   int   OSVersionInfoSize;  
          public   int   majorVersion;    
          public   int   minorVersion;  
          public   int   buildNumber;  
          public   int   platformId;  
   
          [   MarshalAs(   UnmanagedType.ByValTStr,   SizeConst=128   )]          
          public   String   versionString;  
  }  
   
  此例中用到MashalAs特性,它用于描述字段、方法或参数的封送处理格式。用它作为参数前缀并指定目标需要的数据类型。例如,以下代码将两个参数作为数据类型长指针封送给   Windows   API   函数的字符串   (LPStr):    
          [MarshalAs(UnmanagedType.LPStr)]  
  String   existingfile;  
          [MarshalAs(UnmanagedType.LPStr)]  
  String   newfile;  
   
  注意结构作为参数时候,一般前面要加上ref修饰符,否则会出现错误:对象的引用没有指定对象的实例。  
  [   DllImport(   "kernel32",   EntryPoint="GetVersionEx"   )]    
  public   static   extern   bool   GetVersionEx2(   ref   OSVersionInfo2   osvi   );    
   
  三、如何保证使用托管对象的平台调用成功?  
          如果在调用平台   invoke   后的任何位置都未引用托管对象,则垃圾回收器可能将完成该托管对象。这将释放资源并使句柄无效,从而导致平台invoke   调用失败。用   HandleRef   包装句柄可保证在平台   invoke   调用完成前,不对托管对象进行垃圾回收。  
          例如下面:  
                  FileStream   fs   =   new   FileStream(   "a.txt",   FileMode.Open   );  
                  StringBuilder   buffer   =   new   StringBuilder(   5   );  
                  int   read   =   0;  
                  ReadFile(fs.Handle,   buffer,   5,   out   read,   0   );   //调用Win   API中的ReadFile函数  
  由于fs是托管对象,所以有可能在平台调用还未完成时候被垃圾回收站回收。将文件流的句柄用HandleRef包装后,就能避免被垃圾站回收:  
  [   DllImport(   "Kernel32.dll"   )]  
  public   static   extern   bool   ReadFile(    
      HandleRef   hndRef,    
      StringBuilder   buffer,    
      int   numberOfBytesToRead,    
      out   int   numberOfBytesRead,    
      ref   Overlapped   flag   );  
  ......  
  ......  
                  FileStream   fs   =   new   FileStream(   "HandleRef.txt",   FileMode.Open   );  
                  HandleRef   hr   =   new   HandleRef(   fs,   fs.Handle   );  
                  StringBuilder   buffer   =   new   StringBuilder(   5   );  
                  int   read   =   0;  
                  //   platform   invoke   will   hold   reference   to   HandleRef   until   call   ends  
                  ReadFile(   hr,   buffer,   5,   out   read,   0   );   
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值