【发布时间】:2011-04-19 21:33:20
【问题描述】:
math.dll
namespace math
{
public class MyClass {
public static int Add(int x, int y)
{
return x+y;
}
}
在我的 exe 项目中,我想使用 Add() 函数,
示例 1 - 这是有效的
public void Example_1()
{
SampleAssembly = Assembly.Load("math");
Type type = SampleAssembly.GetType("math.MyClass");
MethodInfo methodInfo = type.GetMethod("Add");
if(methodInfo != null)
{
object result = null;
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
object[] parametersArray = new object[] { 3, 5 };
result = methodInfo.Invoke(classInstance, parametersArray);
MessageBox.Show(result.ToString());
}
}
示例 2 - 这不起作用
public delegate int Add(int x,int y);
public void Example_2()
{
SampleAssembly = Assembly.Load("math");
Type type = SampleAssembly.GetType("math.MyClass");
MethodInfo methodInfo = type.GetMethod("Add");
if(methodInfo != null)
{
Add add = (Add)Marshal.GetDelegateForFunctionPointer
(methodInfo.MethodHandle.GetFunctionPointer(),typeof(Add));
MessageBox.Show(add(3,2).ToString());
}
}
示例 3 - 这不起作用
public void Example_3() {
IntPtr hdl = LoadLibrary("math.dll");
IntPtr addr = GetProcAddress(hdl,"MyClass");
IntPtr myfunction = GetProcAddress(addr,"Add");
Add add= (Add)Marshal.GetDelegateForFunctionPointer(hdl,typeof(Add));
MessageBox.Show(add(2,3).ToString());
}
你能告诉我不工作的例子(2,3)的错误在哪里吗? 谢谢。
【问题讨论】:
-
您是否想了解程序集和方法的机制?或者您只是想在外部程序集中使用一种方法?如果是后者,只需将程序集引用添加到您的项目并直接实例化该类。您不需要编写任何这些代码。
-
是的,我知道这是添加参考的最简单方法。正如你所说,我想了解程序集和导出方法。感谢您的建议。
标签: c# dll dllexport loadlibrary getprocaddress