C# 调用Dll 文件

来源:互联网 发布:linux scan 编辑:程序博客网 时间:2024/05/22 02:29


   C# 调用dll的时候,要根据dll的来源选择不同的调用方式。

 (1)非C#语言编写的dll,比如调用Delphi、Java等语言编写的dll:

         第一步, using System.Runtime.InteropServices;

         第二步,声明并静态调用,如下所示:

         

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Management;using System.Net;using System.Net.Sockets;using System.Runtime.InteropServices;namespace MACADDR{    public class ComputerHepler    {        [DllImport("Iphlpapi.dll")]        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);        [DllImport("Ws2_32.dll")]        private static extern Int32 inet_addr(string ip);        public static string strHostName = Dns.GetHostName(); //得到本机的主机名        //获取本机的IP        public static string getLocalIP()        {            IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP            string strAddr = ipEntry.AddressList[0].ToString();   //假设本地为单网卡            return (strAddr);        }        /// <summary>        /// 通过SendArp获取MAC地址        /// </summary>        /// <param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param>        /// <returns>目标机器的mac 地址</returns>        public static string getMacAddr_Remote(string RemoteIP)        {            StringBuilder macAddress = new StringBuilder();            try            {                Int32 remote = inet_addr(RemoteIP);                Int64 macInfo = new Int64();                Int32 length = 6;                SendARP(remote, 0, ref macInfo, ref length);                string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();                int x = 12;                for (int i = 0; i < 6; i++)                {                    if (i == 5)                    {                        macAddress.Append(temp.Substring(x - 2, 2));                    }                    else                    {                        macAddress.Append(temp.Substring(x - 2, 2) + "-");                    }                    x -= 2;                }                return macAddress.ToString();            }            catch            {                return macAddress.ToString();            }        }



 (2)C#语言编写的dll,即调用类库:

        1、在项目里添加引用dll,如下图所示:

         

         2、直接new 一个对象,然后直接调用对象中的方法。

              比如dll中有一个命名空间Test,Test中有一个类C,C中有一个方法M,那么现在调用M的方法如下:

Using Test;

namespace CallDLL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Test.C c = new Test.C();
            MessageBox.Show(c.M());
        }
    }
}

0 0
原创粉丝点击