代码如下:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteFile(
SafeFileHandle hFile,
char[] lpBuffer,
int nNumberOfBytesToWrite,
out int lpNumberOfBytesWritten,
IntPtr lpOverlapped
);问题:“kernel32.dll”“SetLastError”“SafeFileHandle”分别表示什么?这段代码出自票据打印类:http://www.csharpwin.com/csharpspace/9090r8371.shtml请问这段代码的作用是什么?
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteFile(
SafeFileHandle hFile,
char[] lpBuffer,
int nNumberOfBytesToWrite,
out int lpNumberOfBytesWritten,
IntPtr lpOverlapped
);问题:“kernel32.dll”“SetLastError”“SafeFileHandle”分别表示什么?这段代码出自票据打印类:http://www.csharpwin.com/csharpspace/9090r8371.shtml请问这段代码的作用是什么?
解决方案 »
- 老师留任务 用windows窗体做个简单的计算器,可以连续计算的,没有头绪,谁可以指导一下我呀
- 窗体如何重新加载调用load方法
- 求一正则表达式,找html源文件的地址
- dexplore.exe出错导致无法查看msdn2005
- 请教大侠在sql2000中能不能设置成像在access2000库中通过“独占”方式设置密码后才能打开access库的表啊?如果能,能不能说说具体的操作
- DevExpress中GridControl控件的一些问题,请教高手!
- === 针式打印机问题 ===
- 读取excel出现的问题
- Adapter设计模式
- C# 读取整个文档
- 我想请问c# java c++ delphi php那种最好学?
- Print方法。
当在托管应用程序中重用现有的非托管代码时,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);
}
kernel32.dll是MS的WINAPI类库,SafeFileHandle代表文件句柄,此代码就是在类中声明一个和底层楼哭对接的方法,以便C#能调用C++函数
private static extern bool WriteFile(
int hFile, // 通信设备句柄 handle to file
byte[] lpBuffer, // 数据缓冲区 data buffer
int nNumberOfBytesToWrite, // 多少字节等待写入 number of bytes to write
ref int lpNumberOfBytesWritten, // 已经写入多少字节 number of bytes written
ref OVERLAPPED lpOverlapped // 溢出缓冲区 overlapped buffer
);