c#基础知识(四)dll相关
sshong 发表于2013年2月3日 13:00:43 更新于2013年2月6日 23:41:30
dll,动态链接库。
这里区分两个概念,
一个是传统的动态链接库,也是我们所熟知的,如system32下的kerneral.dll,user32.dll,这种dll由c或者c++写的dll编译出来已经是机器码的二进制文件,里面提供一些封装好的函数接口等。这种dll基本上各种语言都能调用。
而c#里又引入了一种dll,这种dll就是一个类库,可以在vs中创建
c#dll


这种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、http://www.cnblogs.com/dayouluo/archive/2005/09/03/229583.html
4、http://webservices.ctocio.com.cn/226/11544726.shtml
标签:dll分类:C#阅读:2587
评论
暂无评论
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅