使用托管代码动态调用非托管的DLLusing System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace InteropDemo
{
    public static class NativeMethod
     {
         [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        public static extern int LoadLibrary(
             [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
         [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        public static extern IntPtr GetProcAddress(int hModule,
             [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
         [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        public static extern bool FreeLibrary(int hModule);
     }
}using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace InteropDemo
{
    class Program
     {
        static void Main(string[] args)
         {
            //1. 动态加载C++ Dll
            int hModule = NativeMethod.LoadLibrary(@"c:\CppDemo.dll");
            if (hModule == 0) return;
            //2. 读取函数指针
             IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");
            //3. 将函数指针封装成委托
             Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));
            //4. 测试
             Console.WriteLine(addFunction(1, 2));
             Console.Read();
         }
        /// <summary>
        /// 函数指针
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        delegate int Add(int a, int b);
     }
}在使用上述这个方法时需要注意什么?
再有还有没有其他的动态调用的方法?

解决方案 »

  1.   

    我记得之前使用那种方法可以动态加载,后来加载不成功了。有没有可能是win32类库中的kernel32.dll问题?
      

  2.   

    使用System.Reflection反射动态加载或者用Emit 动态创建!
      

  3.   

    反射只能动态加载托管代码编写的DLL,不能加载非托管的DLL。
      

  4.   

    你说的用Emit 动态创建?怎么实现呢?
      

  5.   

    http://blog.csdn.net/pansiom/archive/2006/01/01/568096.aspx
      

  6.   

    DllImport必须滴。
    有自己的结构的话。需要定义格式说明
      

  7.   

    DllImport指示该属性化方法由非托管动态链接库(DLL)作为静态入口点公开,不是动态调用的方法。