C#使用技巧--調用DLL
發表于:2007-06-30來源:作者:點擊數:
標簽:
使用C#時不免用調用別的DLL,如WIN32的API和自己以前做的DLL, C#調用DLL很像 VB ,下面討論的C#調用DLL的方式。 看看下面的例子,演示了怎么定義DLL函數接口 public class Utility { [DllImport(kernel32, EntryPoint=”CreateDirectory”, CallingConventio
使用C#時不免用調用別的DLL,如WIN32的API和自己以前做的DLL,
C#調用DLL很像
VB,下面討論的C#調用DLL的方式。
看看下面的例子,演示了怎么定義DLL函數接口
public class Utility
{
[DllImport("kernel32",
EntryPoint=”CreateDirectory”,
CallingConvention=CallingConvention.S
tdCall]
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文檔
原文轉自:http://www.anti-gravitydesign.com