大家在实际工作学习C#的时候,可能会问:为什么我们要为一些已经存在的功能(比如 Windows中的一些功能,C++中已经编写好的一些方法)要重新编写代码,C#有没有方法可以直接都用这些原本已经存在的功能呢?答案是肯定的,大家 可以通过C#中的DllImport直接调用这些功能。
DllImport所在的名字空间 using System.Runtime.InteropServices;
MSDN中对DllImportAttribute的解释是这样的:可将该属性应用于方法。DllImportAttribute 属性提供对从非托管 DLL 导出的函数进行调用所必需的信息。作为最低要求,必须提供包含入口点的 DLL 的名称。
DllImport 属性定义如下:
namespace System.Runtime.InteropServices
{
  [AttributeUsage(AttributeTargets.Method)]
  public class DllImportAttribute: System.Attribute
  {
   public DllImportAttribute(string dllName) {...}
   public CallingConvention CallingConvention;
   public CharSet CharSet;
   public string EntryPoint;
   public bool ExactSpelling;
   public bool PreserveSig;
   public bool SetLastError;
   public string Value { get {...} }
  }

  说明: 
  1、DllImport只能放置在方法声明上。 
  2、DllImport具有单个定位参数:指定包含被导入方法的 dll 名称的 dllName 参数。 
  3、DllImport具有五个命名参数: 
   a、CallingConvention 参数指示入口点的调用约定。如果未指定 CallingConvention,则使用默认值 CallingConvention.Winapi。 
   b、CharSet 参数指示用在入口点中的字符集。如果未指定 CharSet,则使用默认值 CharSet.Auto。 
   c、EntryPoint 参数给出 dll 中入口点的名称。如果未指定 EntryPoint,则使用方法本身的名称。 
   d、ExactSpelling 参数指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配。如果未指定 ExactSpelling,则使用默认值 false。 
   e、PreserveSig 参数指示方法的签名应当被保留还是被转换。当签名被转换时,它被转换为一个具有 HRESULT 返回值和该返回值的一个名为 retval 的附加输出参数的签名。如果未指定 PreserveSig,则使用默认值 true。 
   f、SetLastError 参数指示方法是否保留 Win32"上一错误"。如果未指定 SetLastError,则使用默认值 false。 
  4、它是一次性属性类。 
  5、此外,用 DllImport 属性修饰的方法必须具有 extern 修饰符。

========================================================

    DllImport是System.Runtime.InteropServices命名空间下的一个属性类,其功能是提供从非托管DLL导出的函数的必要调用信息。
    DllImport属性应用于方法,要求最少要提供包含入口点的dll的名称。
    DllImport的定义如下:

        [AttributeUsage(AttributeTargets.Method)] 
  public class DllImportAttribute: System.Attribute
  {
   public DllImportAttribute(string dllName) {…} //定位参数为dllName
public CallingConvention CallingConvention; //入口点调用约定
public CharSet CharSet; //入口点采用的字符接
public string EntryPoint; //入口点名称
public bool ExactSpelling; //是否必须与指示的入口点拼写完全一致,默认false
public bool PreserveSig; //方法的签名是被保留还是被转换
public bool SetLastError; //FindLastError方法的返回值保存在这里
public string Value { get {…} }
  }

用法示例:

    [DllImport("kernel32")] 
private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);

以上是用来写入ini文件的一个win32api。
    
    用此方式调用Win32API的数据类型对应:DWORD=int或uint,BOOL=bool,预定义常量=enum,结构=struct。

DllImport会按照顺序自动去寻找的地方: 1、exe所在目录 2、System32目录 3、环境变量目录所以只需要你把引用的DLL 拷贝到这三个目录下 就可以不用写路径了 或者可以这样server.MapPath(.\bin\*.dll)web中的,同时也是应用程序中的 后来发现用[DllImport(@"C:\OJ\Bin\Judge.dll")]这样指定DLL的绝对路径就可以正常装载。 这个问题最常出现在使用 第三方非托管DLL组件的时候,我的也同样是这时出的问题,Asp.Net Team的官方解决方案如下: 首先需要确认你引用了哪些组件,那些是托管的,哪些是非托管的.托管的很好办,直接被使用的需要引用,间接使用的需要拷贝 到bin目录下.非托管的处理会比较麻烦.实际上,你拷贝到bin没有任何帮助,因为CLR会把文件拷贝到一个临时目录下,然后在那运行web,而CLR 只会拷贝托管文件,这就是为什么我们明明把非托管的dll放在了bin下却依然提示不能加载模块了.  具体做法如下:  首先我们在服务器上随便找个地 方新建一个目录,假如为C:\DLL  然后,在环境变量中,给Path变量添加这个目录  最后,把所有的非托管文件都拷贝到C:\DLL中.  或者 更干脆的把DLL放到system32目录  对于可以自己部署的应用程序,这样未偿不是一个解决办法,然而,如果我们用的是虚拟空间,我们是没办法把注 册PATH变量或者把我们自己的DLL拷到system32目录的。同时我们也不一定知道我们的Dll的物理路径。  DllImport里面只能用字符 串常量,而不能够用Server.MapPath(@"~/Bin/Judge.dll")来确定物理路径。ASP.NET中要使用DllImport 的,必须在先“using System.Runtime.InteropServices;”不过,我发现,调用这种"非托管Dll”相当的慢,可能是因为我的方法需要远程验证 吧,但是实在是太慢了。经过一翻研究,终于想到了一个完美的解决办法首先我们用

[DllImport("kernel32.dll")] 
private extern static IntPtr LoadLibrary(String path); [DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName); [DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);

分别取得了LoadLibrary和GetProcAddress函数的地址,再通过这两个函数来取得我们的DLL里面的函数。
我们可以先用Server.MapPath(@"~/Bin/Judge.dll")来取得我们的DLL的物理路径,然后再用LoadLibrary进行载入,最后用GetProcAddress取得要用的函数地址

以下自定义类的代码完成LoadLibrary的装载和函数调用:

 public class DllInvoke  
{
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path); [DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName); [DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib); private IntPtr hLib; public DllInvoke(String DLLPath)
{
hLib = LoadLibrary(DLLPath);
} ~DllInvoke()
{
FreeLibrary(hLib);
} //将要执行的函数转换为委托
public Delegate Invoke(String APIName,Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
return (Delegate)Marshal.GetDelegateForFunctionPointer(api,t);
}
}

下面代码进行调用

 public delegate int Compile(String command, StringBuilder inf); 
//编译
DllInvoke dll = new DllInvoke(Server.MapPath(@"~/Bin/Judge.dll"));
Compile compile = (Compile)dll.Invoke("Compile", typeof(Compile));
StringBuilder inf;
compile(@“gcc a.c -o a.exe“,inf);//这里就是调用我的DLL里定义的Compile函数

========================================================

DllImport的用法:
DllImport("MyDllImport.dll")]
private static extern int mySum(int a,int b);

一 在C#程序设计中使用Win32类库
常用对应类型:
1、DWORD 是 4 字节的整数,因此我们可以使用 int 或 uint 作为 C# 对应类型。
2、bool 类型与 BOOL 对应。

示例一:调用 Beep() API 来发出声音
Beep() 是在 kernel32.lib 中定义的,在MSDN 中的定义,Beep具有以下原型:
BOOL Beep(DWORD dwFreq, // 声音频率
DWORD dwDuration // 声音持续时间);
用 C# 编写以下原型:
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);

示例二:枚举类型和常量
MessageBeep() 是在 user32.lib 中定义的,在MSDN 中的定义,MessageBeep具有以下原型:
BOOL MessageBeep(UINT uType // 声音类型
);

用C#编写一下原型:
public enum BeepType
{
  SimpleBeep = -1,
  IconAsterisk = 0x00000040,
  IconExclamation = 0x00000030,
  IconHand = 0x00000010,
  IconQuestion = 0x00000020,
  Ok = 0x00000000,
}
uType 参数实际上接受一组预先定义的常量,对于 uType 参数,使用 enum 类型是合乎情理的。
[DllImport("user32.dll")]
public static extern bool MessageBeep(BeepType beepType);

示例三:处理结构
有时我需要确定我笔记本的电池状况。Win32 为此提供了电源管理函数,搜索 MSDN 可以找到GetSystemPowerStatus() 函数。
BOOL GetSystemPowerStatus(
  LPSYSTEM_POWER_STATUS lpSystemPowerStatus
);
此函数包含指向某个结构的指针,我们尚未对此进行过处理。要处理结构,我们需要用 C# 定义结构。我们从非托管的定义开始:
typedef struct _SYSTEM_POWER_STATUS {
BYTE  ACLineStatus;
BYTE  BatteryFlag;
BYTE  BatteryLifePercent;
BYTE  Reserved1;
DWORD BatteryLifeTime;
DWORD BatteryFullLifeTime;
} SYSTEM_POWER_STATUS, *LPSYSTEM_POWER_STATUS;
   然后,通过用 C# 类型代替 C 类型来得到 C# 版本。
struct SystemPowerStatus
{
  byte ACLineStatus;
  byte batteryFlag;
  byte batteryLifePercent;
  byte reserved1;
  int batteryLifeTime;
  int batteryFullLifeTime;
}
这样,就可以方便地编写出 C# 原型:
[DllImport("kernel32.dll")]
public static extern bool GetSystemPowerStatus(
  ref SystemPowerStatus systemPowerStatus);
   在此原型中,我们用“ref”指明将传递结构指针而不是结构值。这是处理通过指针传递的结构的一般方法。
   此函数运行良好,但是最好将 ACLineStatus 和 batteryFlag 字段定义为 enum:
  enum ACLineStatus: byte
   {
    Offline = 0,
    Online = 1,
    Unknown = 255,
   }
   enum BatteryFlag: byte
   {
    High = 1,
    Low = 2,
    Critical = 4,
    Charging = 8,
    NoSystemBattery = 128,
    Unknown = 255,
   }
请注意,由于结构的字段是一些字节,因此我们使用 byte 作为该 enum 的基本类型

示例四:处理字符串

二 C# 中调用C++代码
int 类型
[DllImport(“MyDLL.dll")]
//返回个int 类型
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改变a1 b1
//a2=..
//b2=...
return a+b;
}

//参数传递int 类型
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int *a2,int *b2)
{
//可以改变 a1, b1
*a2=...
*b2=...
return a+b;
}

DLL 需传入char *类型
[DllImport(“MyDLL.dll")]
//传入值
public static extern int mySum (string astr1,string bstr1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr2,char * bstr2)
{
//改变astr2 bstr 2 ,astr1 bstr1不会被改变
return a+b;
}

DLL 需传出char *类型
[DllImport(“MyDLL.dll")]
// 传出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr,char * bstr)
{
//传出char * 改变astr bstr -->abuf, bbuf可以被改变
return a+b;
}

DLL 回调函数

BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)

using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam); //定义委托函数类型
public class EnumReportApp
{
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main() {
CallBack myCallBack = new CallBack(EnumReportApp.Report); EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd); return true;
}
}

DLL 传递结构
BOOL PtInRect(const RECT *lprc, POINT pt);

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}
Class XXXX {
[DllImport("User32.dll")]
public static extern bool PtInRect(ref Rect r, Point p);
}

.Net中C#的DllImport的用法的更多相关文章

  1. 【转帖】.Net中C#的DllImport的用法

    在 C# 中通过 P/Invoke 调用Win32 DLL http://msdn.microsoft.com/zh-cn/library/aa686045.aspx   大家在实际工作学习C#的时候 ...

  2. C# DllImport的用法

    大家在实际工作学习C#的时候,可能会问:为什么我们要为一些已经存在的功能(比如Windows中的一些功能,C++中已经编写好的一些方法)要重新编写代码,C#有没有方法可以直接都用这些原本已经存在的功能 ...

  3. Spring mvc中@RequestMapping 6个基本用法

    Spring mvc中@RequestMapping 6个基本用法 spring mvc中的@RequestMapping的用法.  1)最基本的,方法级别上应用,例如: Java代码 @Reques ...

  4. Delphi中stringlist分割字符串的用法

    Delphi中stringlist分割字符串的用法 TStrings是一个抽象类,在实际开发中,是除了基本类型外,应用得最多的. 常规的用法大家都知道,现在来讨论它的一些高级的用法. 1.CommaT ...

  5. Linq中关键字的作用及用法

    Linq中关键字的作用及用法 1.All:确定序列中的所有元素是否都满足条件.如果源序列中的每个元素都通过指定谓词中的测试,或者序列为空,则为 true:否则为 false. Demo: 此示例使用 ...

  6. 标准C++中的string类的用法总结

    标准C++中的string类的用法总结 相信使用过MFC编程的朋友对CString这个类的印象应该非常深刻吧?的确,MFC中的CString类使用起来真的非常的方便好用.但是如果离开了MFC框架,还有 ...

  7. html中的alt和title用法区别

    html中的alt和title用法区别 首先明确一下概念,alt是html标签的属性,而title既是html标签,又是html属性.title标签这个不用多说,网页的标题就是写在<title& ...

  8. HTML中的target(_self,_blank)用法总结

    HTML中的target(_self,_blank)用法总结 最近一个项目,多次遇到target='_self', target='_blank'的用法, 再次总结一下: 1.<a>标签 ...

  9. jquery中append跟prepend的用法

    jquery中append和prepend的用法 append   是插入到元素中,并放到元素内的最后面prepend  是插入到元素中,并放到元素内的最前面例$("body"). ...

随机推荐

  1. ###《Machine Learning in Action》 - KNN

    初学Python:理解机器学习. 算法是需要实现的,纸上得来终觉浅. // @author: gr // @date: 2015-01-16 // @email: forgerui@gmail.com ...

  2. SVN服务器从Windows迁移到Linux

    gerui 2013.9.14 ge-rui@sohu.com 一.备份VisualSVN项目 1. 现在要使用Linux作为svn服务器,之前是在windows Server 2008上的,用的是V ...

  3. 一个layer可以跟着画完的线移动ios程序 好玩啊。

    用法:采用的是关键帧实现的. 实验目的:让上层的layer子层能够跟着在另一个子层上花的线进行移动 .即当线画完之后,图形开始移动,并且能够停在最后的那个位置 效果图: 采用是直接在layer图层上进 ...

  4. 初学java,遇到的陌生词语(1)

    字节码文件:不包含硬件信息,完全与硬件平台无关,因此,无法直接由操作系统来运行. Java应用程序的执行过程:代码装入.代码检验.代码执行. 1.代码装入:由类装配器完成,装入程序运行时所需的所有源代 ...

  5. ifstream:incomplete type is not allowed

    IntelliSense: incomplete type is not allowed ifstream inputFile; Need to add this: #include <fstr ...

  6. 数据库不能用delete---index空间不足

    只有0702表是这样的情况,0101表可以使用like和between and

  7. Windows和Linux下查看Apache、MySQL、PHP版本

    # Windows查看Apache版本: 使用命令:httpd -v # Linux查看Apache版本: 使用命令:apachectl -v # Windows查看MySQL版本: 使用命令:mys ...

  8. jquery 里面的$(document).ready 和 DOMContentLoaded

    DOMContentLoaded 事件是当页面的初始dom tree加载好了就会执行. 而不会去等待外部的css 渲染完成和 js执行完成,即下图中的DOM Tree阶段 DOMContentLoad ...

  9. 关于2440的裸跑程序中SD卡读后不能成功写入问题的讨论

    问题描述: TQ2440的官方裸跑程序中,对SD卡先进行读操作,然后再写,发现不能程序卡死.倘若对SD卡先写后读,程序可以正常运行,奇哉怪哉? 写数据的关键代码--> while(i < ...

  10. 开发设计模式(四) 代理模式(Proxy Pattern)

    转自http://blog.sina.com.cn/s/blog_89d90b7c0101803g.html 代理模式:代理模式的主要作用是为其他对象提供一种代理以控制对这个对象的访问.在某些情况下, ...