代码如下:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(
SafeFileHandle hObject
);出自票据打印类:http://www.csharpwin.com/csharpspace/9090r8371.shtml
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(
SafeFileHandle hObject
);出自票据打印类:http://www.csharpwin.com/csharpspace/9090r8371.shtml
当在托管应用程序中重用现有的非托管代码时,DllImport 属性非常有用。例如,托管应用程序可能需要调用非托管 WIN32 API。下面的代码示例说明此通用方案,此示例将调用 MessageBox(位于 User32.lib 中):#using <mscorlib.dll>
using namespace System::Runtime::InteropServices;
// for DllImportAttributenamespace SysWin32
{
[DllImport("user32.dll", EntryPoint = "MessageBox", CharSet = Unicode)]
int MessageBox(void* hWnd, wchar_t* lpText, wchar_t* lpCaption,
unsigned int uType);
}int main( )
{
SysWin32::MessageBox( 0, L"Hello world!", L"Greetings", 0 );
}
主要注意包含 DllImport 的代码行。此代码行根据参数值通知编译器,使之声明位于 User32.dll 中的函数并将签名中出现的所有字符串(如参数或返回值)视为 Unicode 字符串。如果缺少 EntryPoint参数,则默认值为函数名。另外,由于 CharSet 参数指定 Unicode,因此公共语言运行库将首先查找称为 MessageBoxW(有 W 是因为 Unicode 规范)的函数。如果运行库未找到此函数,它将根据调用约定查找 MessageBox 以及相应的修饰名。受支持的调用约定只有 __cdecl 和 __stdcall。当调用用户定义的 DLL 中所包含的函数时,有必要将 extern "C" 添加在 DLL 函数声明之前,如下所示:// The function declaration in SampleDLL.h file
extern "C" SAMPLEDLL_API int fnSampleDLL(void);
有关受支持的其他参数值的更多信息,请参见 DllImport。将非结构化参数由托管封送处理为非托管
除使用上述方法外,还可以使用另一种方法将托管参数(来自托管应用程序)封送处理为非托管参数(在非托管 DLL 中)。以下代码示例说明封送处理技术:#using <mscorlib.dll>
using namespace System; // To bring System::String in
using namespace System::Runtime::InteropServices;
// for DllImportAttribute
namespace SysWin32
{
[DllImport("user32.dll", EntryPoint = "MessageBox", CharSet = Unicode)]
Int32 MessageBox( Int32 hWnd, String* lpText, String* lpCaption,
UInt32 uType );
}int main( )
{
SysWin32::MessageBox(0, S"Hello world!", S"Greetings", 0);
}
你可以搜索关键字:c# p/invoke
msdn
http://msdn.microsoft.com/zh-cn/library/aa686045.aspx