jeudi 25 juin 2015

C# Reflection Method Invoke (ref parameter)

To get to the point of what I need, I will use this simplified example.

I have a .DLL file, located in C:/test.dll

public class CLASS{
    public void METHOD(ref int A){
        A = 5;
    }
}

I have my program, in C:/Program.exe

// Variables
Assembly DLL;
Type TARGETTYPE;
object TARGETINSTANCE;
MethodInfo TARGETMethod;

public class Program{
    public void Main(){
        SetupReflection();
        int A = 0;
        DoThing(ref A);
        MessageBox.Show(A.ToString()); // I expect '5'
    }    
}

The methods:

// Links DLL and Method
void SetupReflection(){
    DLL = Assembly.LoadFile( @"C:/test.dlll" );
    TargetType = DLL.GetExportedTypes()[0]; // CLASS
    TargetInstance = Activator.CreateInstance( TargetType );
    TargetMethod = TargetType.GetMethod("METHOD");
}

// Ask the DLL to modify my values
void DoThing(ref int A){
    A = 1; // This works
    object[] args = new object[]{ A }; // Required by .Invoke
    TargetMethod.Invoke(TargetInstance, args).ToString();
}

I seem to get a

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe Additional information: Object reference not set to an instance of an object.

What do I modify inside of DoThing to make this work?

The object "int A" is there for simplicity. In its place, I have a massive amount of data, that can NEVER just be copied back and forth, as my program is time-critical.

All I need to be able to do, is load and unload .DLL files dynamically at run-time, and ask them to work with my massive amounts of data, without any copying. If I do not use the "ref", methods are not allowed to modify the passed data.





Aucun commentaire:

Enregistrer un commentaire