您的位置:首页 > 编程语言 > C#

c#基础知识4:dll相关

2012-10-24 11:32 246 查看
dll,动态链接库。

这里区分两个概念,

一个是传统的动态链接库,也是我们所熟知的,如system32下的kerneral.dll,user32.dll,这种dll由c或者c++写的dll编译出来已经是机器码的二进制文件,里面提供一些封装好的函数接口等。这种dll基本上各种语言都能调用。

而c#里又引入了一种dll,这种dll就是一个类库,可以在vs中创建



这种dll虽然编译出来也是二进制的,不过是c#的中间码格式,不同于传统的dll。只能供c#使用,仅仅是一个类库。

c#里调用第二种dll不用说了,非常简单,拷过来代码里就能引入。

这里主要讲c#如何调用第一种传统的dll,譬如windows的api。

声明一个extern函数来托管外部dll中的一个函数。如想要调用win32的msgbox

/*
* Author: Shu
* E_mail: shushenghong@gmail.com
* Time: 10/24/2012 10:19:48 AM
*/
using System;
using System.Runtime.InteropServices;

/// <summary>
/// win32的alert
/// </summary>
public class Alert
{
[DllImport("user32.dll", EntryPoint = "MessageBox", CharSet = CharSet.Unicode)]
private static extern int DllMsgBox(int hwnd, string content, string title, uint type);

/// <summary>
/// win32的消息框
/// </summary>
public static void MsgBox(string content, string title)
{
DllMsgBox(0, content, title, 64);
}
}


具体dllImport有哪些属性,可以参看msdn。

http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.dllimportattribute.aspx

声明的函数必须与dll中的函数形参一致,具体的类型对应,可以参考

http://msdn.microsoft.com/zh-cn/library/aa720411(en-us,VS.71).aspx

参考资料:

1、http://developer.51cto.com/art/200908/146253.htm

2、http://www.cnblogs.com/cltsq/articles/1946395.html

3、/article/4995237.html

4、http://webservices.ctocio.com.cn/226/11544726.shtml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: