C#动态库调用方法

C#预研对动态库有两种调用方法,和VC++,操作方法差不多,但是概念发生变化。分为动态加载和静态加载。

1) 动态加载,使用映射的原理,主程序需要添加 using System.Reflection; 具体看例子比较详细,分动态库部分和主程序部分。

动态库:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MT.MTCSPI.C1200
{
    public class checkweigherC1200
    {
        string name;
        int port;

        public static string getHelloName(string tm)
        {
            string tmp = tm;
            return "hello" + tmp;
        }
    }
}


主程序调用:

            assemblyAA = Assembly.LoadFrom("C:\\DevelopIDE\\C#\\VS2012\\PC\\DllTestExample\\DllTest\\MT.MTCSPI.C1200\\bin\\Debug\\MT.MTCSPI.C1200.dll");
            typeCheckweigherC1200 = assemblyAA.GetType("MT.MTCSPI.C1200.checkweigherC1200");
            Object objC1200 = Activator.CreateInstance(typeCheckweigherC1200);
            MethodInfo HelloNameMeth = typeCheckweigherC1200.GetMethod("getHelloName");
            string objNew = Convert.ToString(HelloNameMeth.Invoke(objC1200, new Object[1] {"abcd"}));
            textBox1.Text = objNew;

2) 静态调用, 这种方法把编译出来的动态库应用到主程序里,主程序利用空间名和类名就可以直接调用。

动态库:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamic.Library.Checkweigher
{
    public class Device
    {
        public Device()
        {
            Valid = false;
        }

        public static string Name { get; set; }

        public string IpAddress { get; set; }

        public int Port { get; set; }

        public bool Valid { get; set; }

        public static string getCheckweighername(string tmp)
        {
            return tmp + "CW";
        }

        public int getIpAddr()
        {
            return 192;
        }
    }
}


主程序调用1:           

            string strTmp = Device.getCheckweighername("Lin Ye");
            Device.Name = "hello static";
            strTmp = Device.Name;
            textBox1.Text = strTmp;

            int ipAddr = 0;
            Device detailDevice = new Device();
            MethodInfo method = typeof(Device).GetMethod("getIpAddr");

            ipAddr = Convert.ToInt32(method.Invoke(detailDevice, new Object[0] { }));
            textBox1.Text = ipAddr.ToString();






你可能感兴趣的:(CSharp,Development)