问题遇到的现象和发生背景
使用c#测试动态加载托管dll,通过LoadLibrary可以加载到dll,但是GetProcAddress加载函数时返回0,错误代码为 127,错误信息为 找不到指定的程序
但是通过实例化dll中的对象,却可以使用函数
问题相关代码,请勿粘贴截图
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using ClassLibrary1;
namespace ClassLibrary1
{
class Program
{
[DllImport("kernel32", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32", EntryPoint = "GetProcAddress", SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32", EntryPoint = "FreeLibrary", SetLastError = true)]
static extern bool FreeLibrary(IntPtr hModule);
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
public extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
static void Main(string[] args)
{
string path = @"E:\C#P\DLLTest01\ClassLibrary1\bin\Debug\ClassLibrary1.dll";
//使用GetProcAddress无法使用
IntPtr handel = Test.LoadLibrary(path);//有值 95354880
IntPtr addr = Test.GetProcAddress(handel, "mess");//addr = 0
if (addr == IntPtr.Zero)
{
int errCode = Marshal.GetLastWin32Error();//127
IntPtr tempptr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr);//找不到指定的程序
}
//创建对象可以
Class1 c = new Class1();
c.mess("hello");//弹框
}
}
}
dll中的代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace ClassLibrary1
{
public class Class1
{
public void mess(string s)
{
MessageBox.Show(s);
}
}
}
运行结果及报错内容
我的解答思路和尝试过的方法
通过dumpbin解析dll,发现没有函数名
但是在vs对象查看器中可以看到mess