0

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)が機能しないことの間違いはどこにあるのか教えてください。ありがとう。

4

1 に答える 1

2

例2と3ではMarshal.GetDelegateForFunctionPointer、アンマネージ関数ポインターをマネージデリゲートに変換するためにアンマネージコードを操作するときに使用される関数であるを使用しています。アセンブリにはマネージ.NETコードが含まれているため、例1のmathようにReflectionを使用する必要があります。したがって、アンマネージC、C ++、...ライブラリの機能を再利用する場合を除いて、この関数は使用しないでください。

アンマネージコード(C、C ++、...)とマネージコード(.NET)を実際に区別する必要があります。

于 2011-04-19T21:39:33.703 に答える