例如:
class CreateInstance
    {
       public string dllName;
       public string methodName;        [DllImport(dllName, EntryPoint = methodName)]
        
        public static void Test()
        {
           ……
        } 请问红色标示部分如何实现??谢谢

解决方案 »

  1.   


    using System;
    using System.Runtime.InteropServices;namespace CallDLL
    {
        class Win32
        {
            /// <summary> 
            /// 原型是 :HMODULE LoadLibrary(LPCTSTR lpFileName); 
            /// </summary> 
            /// <param name="lpFileName">DLL 文件名 </param> 
            /// <returns> 函数库模块的句柄 </returns> 
            [DllImport("kernel32.dll")]
            public static extern IntPtr LoadLibrary(string lpFileName);        /// <summary> 
            /// 原型是 : FARPROC GetProcAddress(HMODULE hModule, LPCWSTR lpProcName); 
            /// </summary> 
            /// <param name="hModule"> 包含需调用函数的函数库模块的句柄 </param> 
            /// <param name="lpProcName"> 调用函数的名称 </param> 
            /// <returns> 函数指针 </returns> 
            [DllImport("kernel32.dll")]
            public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);        /// <summary> 
            /// 原型是 : BOOL FreeLibrary(HMODULE hModule); 
            /// </summary> 
            /// <param name="hModule"> 需释放的函数库模块的句柄 </param> 
            /// <returns> 是否已释放指定的 Dll</returns> 
            [DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)]
            public static extern bool FreeLibrary(IntPtr hModule);
        }
    }
    using System;
    using System.Collections;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Runtime.InteropServices;namespace CallDLL
    {
        internal class DLLInfo
        {
            private IntPtr hModule;
            private ModuleBuilder moduleBuilder;
            private Hashtable methodTable;        internal DLLInfo(IntPtr hModule, ModuleBuilder moduleBuilder)
            {
                this.hModule = hModule;
                this.moduleBuilder = moduleBuilder;
                this.methodTable = new Hashtable();
            }        internal object CallMethod(string methodName, object[] paramArray, Type returnType)
            {
                if (methodTable.ContainsKey(methodName))
                {
                    return (methodTable[methodName] as MethodInfo).Invoke(0,paramArray);
                }
                else
                {
                    MethodInfo methodInfo=this.CreateMethod(methodName,paramArray,returnType);
                    methodTable.Add(methodName, methodInfo);
                    return methodInfo.Invoke(null,paramArray);
                }
            }
            private MethodInfo CreateMethod(string methodName, object[] parameters, Type returnType)
            {
                IntPtr ptrfun = Win32.GetProcAddress(this.hModule, methodName);            if (ptrfun == IntPtr.Zero)
                {
                    throw new Exception(string.Format("Get method {0} error!",methodName));
                }            Type[] paramTypes = new Type[parameters.Length];            for (int i = 0; i < parameters.Length; i++)
                {
                    paramTypes[i] = parameters[i].GetType();
                }            //Create Global Method
                MethodBuilder methodBuilder = moduleBuilder.DefineGlobalMethod(
                                                            methodName,
                                                            MethodAttributes.Public | MethodAttributes.Static,
                                                            returnType,
                                                            paramTypes);
                
                // 获取一个 ILGenerator ,用于发送所需的 IL 
                ILGenerator genIL = methodBuilder.GetILGenerator();            for (int i = 0; i < paramTypes.Length; i++)
                {
                    //By-Ref given parameters.
                    genIL.Emit(OpCodes.Ldarg, i);
                }            if (IntPtr.Size == 4)
                {
                    // 判断处理器类型 
                    genIL.Emit(OpCodes.Ldc_I4, ptrfun.ToInt32());
                }
                else if (IntPtr.Size == 8)
                {
                    genIL.Emit(OpCodes.Ldc_I8, ptrfun.ToInt64());
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }            genIL.EmitCalli(OpCodes.Calli, CallingConvention.Cdecl, returnType, paramTypes);
                genIL.Emit(OpCodes.Ret); // 返回值
                moduleBuilder.CreateGlobalFunctions();            //取得方法信息 
                return moduleBuilder.GetMethod(methodName);
            }
            internal void UnLoadDLL()
            {
                Win32.FreeLibrary(this.hModule);
                this.hModule = IntPtr.Zero;
            }
        }
    }using System;
    using System.Collections;
    using System.Text;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Runtime.InteropServices;
    using System.IO;namespace CallDLL
    {
        public class DLLLoader
        {        private static DLLLoader dllLoader = null;
            
            private AssemblyBuilder assemblyBuilder = null;
            
            private const string DynamicAssemlyName = "Atos.AutoLoad";        private Hashtable DLLInfoTable = null;        private DLLLoader()
            {
                this.assemblyBuilder=AppDomain.CurrentDomain.DefineDynamicAssembly(
                                                 new AssemblyName(DLLLoader.DynamicAssemlyName),
                                                 AssemblyBuilderAccess.Run);            this.DLLInfoTable = new Hashtable();
            }        public static DLLLoader Instance
            {
                get
                {
                    if (DLLLoader.dllLoader == null)
                    {
                        DLLLoader.dllLoader= new DLLLoader();
                        
                    }
                    return DLLLoader.dllLoader;
                }
            }        private DLLInfo GetDLLInfo(string dllFileName)
            {
                if (DLLInfoTable.ContainsKey(dllFileName))
                {
                    return (DLLInfo)DLLInfoTable[dllFileName];
                }
                else
                {
                    DLLInfo dllInfo = this.CreateDLLInfo(dllFileName);
                    DLLInfoTable.Add(dllFileName, dllInfo);
                    return dllInfo;
                }
            }        private DLLInfo CreateDLLInfo(string dllFileName)
            {            IntPtr hModel = Win32.LoadLibrary(dllFileName);            if (hModel == IntPtr.Zero)
                {
                    throw new Exception(string.Format("Load DLL:{0} error!",dllFileName));
                }            //Create Module
                ModuleBuilder moduleBuilder = this.assemblyBuilder.DefineDynamicModule(dllFileName);            return new DLLInfo(hModel, moduleBuilder);
            }        public object CallMethod(string dllFileName,string methodName,object[] parameters,Type returnType)
            {
                DLLInfo dllInfo = this.GetDLLInfo(dllFileName);
                return dllInfo.CallMethod(methodName, parameters, returnType);
            }
            public void UnLoadDLL()
            {
                foreach (DLLInfo dllInfo in DLLInfoTable.Values)
                {
                    dllInfo.UnLoadDLL();
                }
            }
        }
    }
    using System;namespace CallDLL
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                   int i = (int)CallDLL.DLLLoader.Instance.CallMethod("user32.dll", "MessageBoxA", new object[] { IntPtr.Zero, "dddf", "test", (uint)0 }, typeof(int));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    CallDLL.DLLLoader.Instance.UnLoadDLL();
                }
            }
        }
    }