0

数学.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)的错误在哪里吗?谢谢。

4

1 回答 1

2

在示例 2 和 3 中,您使用Marshal.GetDelegateForFunctionPointerwhich 是处理非托管代码时使用的函数,以便将非托管函数指针转换为托管委托。该math程序集包含托管 .NET 代码,因此您应该像示例 1 中一样使用反射。因此,除非您尝试重用非托管 C、C++、... 库中的功能,否则不要使用此函数。

您确实应该区分非托管(C、C++、...)和托管代码(.NET)。

于 2011-04-19T21:39:33.703 回答