C#使用技巧--調用DLL

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- C#使用技巧--調用DLL (http://www.webasp.net/article/6/5590.htm)
-- 作者:未知
-- 發佈日期: 2003-07-12
使用C#時不免用調用別的DLL,如WIN32的API和自己以前做的DLL,
C#調用DLL很像VB,下面討論的C#調用DLL的方式。
看看下面的例子,演示了怎麼定義DLL函數接口
public class Utility
{
   [DllImport("kernel32",
EntryPoint=」CreateDirectory」,
CallingConvention=CallingConvention.StdCall]
   public static extern bool Create (string name);
  
   [DllImport("User32"]
EntryPoint=」MessageBox」,
CallingConvention=CallingConvention.StdCall]
   public static extern int MsgBox (string msg);
}
  
class MyClass
{
   public static int Main()
   {
      string myString;
      Console.Write("Enter your message: ");
      myString = Console.ReadLine();
      return Utility.MsgBox(myString);
   }
}
  
值得注意的是,缺省的調用規則(CallingConvention)是Stdcall,同Winapi,在
C++裡是__stdcall的形式,函數入口(EntryPoint)缺省是同名,如CreateDirectory
的定義也可以為
   [DllImport("kernel32")]
   static extern bool CreateDirectory(string name, SecurityAttributes sa);
  
WIN32 API原型為
BOOL CreateDirectory(
  LPCTSTR lpPathName,                         // directory name
  LPSECURITY_ATTRIBUTES lpSecurityAttributes  // SD
);
  
在調用WIN32 API時注意那些類型的轉換,如結構(struct)、指針(pointer),

有關各種語言之間類型轉換和DllImport屬性的詳細信息可以參考SDK文檔 

webasp.net