.NET 互操作
首先推荐一本书《精通.NET 互操作》 ,这本书是目前中文资料里讲 互操作最详尽的书了。
做系统集成项目的同学应该都和设备打过交道(如视频设备:海康、大华等),在大多数情况下这些设备厂商会给系统集成厂商开发协议(dll 类库、 函数定义的头文件、测试程序、调用流程),这些协议的dll 大都用C++开发的,那么我们用C#集成,就得用 P/Invoke 技术(.NET 互操作的一种)
一、P/Invoke 简单例子
P/Invoke 说白了,就是你调用协议dll 的函数,传入正确的参数(注意C++与C#的数据类型转换)
例子:
1 using System.Runtime.InteropServices; 2 3 class App 4 { 5 [DllImport("msvcrt.dll")] 6 static extern int puts(string msg); 7 8 [DllImport("msvcrt.dll")] 9 static extern int _flushall(); 10 11 static void Main() 12 { 13 puts("Hello World"); 14 _flushall(); 15 CreateMsgWindow(); 16 } 17 18 19 [DllImport("user32.dll",EntryPoint="MessageBox")] 20 static extern int MessageBox(int hwnd,string lpText,string lpCaption,int wType); 21 22 static void CreateMsgWindow() 23 { 24 MessageBox(0,"Hello world!","Welcome",0); 25 } 26 }
二、两款 dll 函数查看工具
1. Dll Export Viewer
2. Dll 函数查看器 2.0
三、C#与C++常见类型对比
C++ 类型 | C# 类型 |
HANDLE (void *)括号内是等价类型 | IntPtr |
Byte(unsigned char) | byte |
SHORT(short) | short |
WORD(unsigned short) | short |
INT(int) | int |
int* | ref int |
UINT(unsigned int) | int |
LONG(long) | int |
ULONG(unsigned long) | uint |
DWORD(unsigned long) | uint |
BOOL(long) | bool |
PCAHR(char *) | string |
char[] | string |
PBYTE(byte *) | byte[] |
结构体 | publlic struct 结构体{} |
char **变量名 | ref string 变量名 |
结构体封装
1 // 协议头文件中的结构体 2 typedef struct 3 { 4 char sLibName[ 256 ]; 5 char sPathToLibrary[ 256 ]; 6 INT32 iEntries; 7 INT32 iUsed; 8 UINT16 iSort; 9 UINT16 iVersion; 10 BOOLEAN fContainsSubDirectories; 11 INT32 iReserved; 12 } LIBHEADER; 13 14 // C#协议包裹类中的对应结构 15 [StructLayout(LayoutKind.Sequential)] 16 public struct LIBHEADER 17 { 18 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] 19 public char[] sLibName; 20 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] 21 public char[] sPathToLibrary; 22 public int iEntries; 23 public int iUsed; 24 public ushort iSort; 25 public ushort iVersion; 26 public bool fContainsSubDirectories; 27 public int iReserved; 28 }
附:
2. Dll Export Viewer 下载
3. Dll 函数查看器 2.0 下载