在Visual Studio写cs文件,调用非托管的win32 api要用到DllImport ,比如
1 using System;
2 using System.Runtime.InteropServices;
3
4 class Example
5 {
6 // Use DllImport to import the Win32 MessageBox function.
7 [DllImport("user32.dll", CharSet = CharSet.Auto)]
8 public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
9
10 static void Main()
11 {
12 // Call the MessageBox function using platform invoke.
13 MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
14 }
15 }
16
2 using System.Runtime.InteropServices;
3
4 class Example
5 {
6 // Use DllImport to import the Win32 MessageBox function.
7 [DllImport("user32.dll", CharSet = CharSet.Auto)]
8 public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
9
10 static void Main()
11 {
12 // Call the MessageBox function using platform invoke.
13 MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
14 }
15 }
16
我常常有这样问题:
DllImport和public static这2行中最重要的部分要手动敲进去,比如函数名MessageBox和参数列表(IntPtr hWnd, String text, String caption, uint type),为什么强大的Visual Studio不能自动完成?
我觉得如果Visual Studio做的比较人性化的话,应该这样:
在*.cs文件上点击右键,出来菜单“调用win api”或“DllImport”,弹出dll文件选择窗口(这里可以把常用win32 dll列出来,免得去system32里找),选择dll文件,确定,弹出dll的函数列表,每个函数名前面有个checkbox,选中checkbox,确定,自动将
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
插入到cs文件的头部,并且自动把函数的参数列表转换成csharp类型且填写完成,多爽,为什么ms没做,不应该是没想到。获取函数名可以使用 dumpbin /exports user32.dll 或 link /dump /exports user32.dll 命令。
最令我比较烦恼的是参数列表和参数类型。假如第三方厂商丢给你一个crypt.dll,没有文档,老板让你用c#调用crypt.dl实现产品的部分功能,即使我用了dumpbin 获取了函数列表,但是我不知道参数啊,是不是就无法完成了?还有,假如有些函数参数不是c#的基本数据类型,是不是也没办法做?大家说说看。
本人菜鸟不才,请园友不吝赐教。