是否可以枚举 DLL 中存在的每个函数?得到它的签名怎么样?我可以在 C# 中执行此操作吗?还是我必须降低水平才能做到这一点?
问候和 tks, 何塞
如果是 .NET DLL ,RedGate 的 Reflector可以列出方法,甚至尝试反汇编代码。对于任何开发人员的工具箱来说,它都是一个很棒的项目,而且它是免费的
编辑:如果您尝试在运行时读取类型和方法,您将需要使用反射。您将不得不加载Assembly
and GetExportedTypes
。然后,迭代Members
到Methods
and Properties
。这是来自 MSDN 的一篇文章,其中有一个迭代MemberInfo
信息的示例。此外,还有一篇 MSDN 杂志文章,从 .NET 程序集中提取数据。
最后,这是我为在加载的对象上执行方法而编写的一个小测试方法。
在这个例子中 ClassLibrary1 有一个 Class1 类:
public class Class1
{
public bool WasWorkDone { get; set; }
public void DoWork()
{
WasWorkDone = true;
}
}
这是测试:
[TestMethod]
public void CanExecute_On_LoadedClass1()
{
// Load Assembly and Types
var assm = Assembly.LoadFile(@"C:\Lib\ClassLibrary1.dll");
var types = assm.GetExportedTypes();
// Get object type informaiton
var class1 = types.FirstOrDefault(t => t.Name == "Class1");
Assert.IsNotNull(class1);
var wasWorkDone = class1.GetProperty("WasWorkDone");
Assert.IsNotNull(wasWorkDone);
var doWork = class1.GetMethod("DoWork");
Assert.IsNotNull(doWork);
// Create Object
var class1Instance = Activator.CreateInstance(class1.UnderlyingSystemType);
// Do Work
bool wasDoneBeforeInvoking =
(bool)wasWorkDone.GetValue(class1Instance, null);
doWork.Invoke(class1Instance, null);
bool wasDoneAfterInvoking =
(bool)wasWorkDone.GetValue(class1Instance, null);
// Assert
Assert.IsFalse(wasDoneBeforeInvoking);
Assert.IsTrue(wasDoneAfterInvoking);
}
如果它是托管 dll:使用反射
如果它是非托管的:您需要枚举 DLL 导出表
您可以使用 Dependency Walker 来查看 dll 中的所有导出,这是 Microsoft 的免费程序:http ://en.wikipedia.org/wiki/Dependency_walker
对于常规 win32 DLL,请参阅Dumpbin 实用程序。它包含在 Visual-C++ 中(包括我相信的免费“快速”版本)。
例子:
c:\vc9\bin\dumpbin.exe /exports c:\windows\system32\kernel32.dll