Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter as a reference with MethodInfo.Invoke

How can I pass a parameter as a reference with MethodInfo.Invoke?

This is the method I want to call:

private static bool test(string str, out byte[] byt) 

I tried this but I failed:

byte[] rawAsm = new byte[]{}; MethodInfo _lf = asm.GetType().GetMethod("test", BindingFlags.Static |  BindingFlags.NonPublic); bool b = (bool)_lf.Invoke(null, new object[] {     "test",     rawAsm }); 

The bytes returned are null.

like image 275
method Avatar asked Jan 08 '12 17:01

method


People also ask

How is a method invoked with parameter?

The invoke () method of Method class Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters automatically to match primitive formal parameters.

What invoke () method do in C#?

This method dynamically invokes the method reflected by this instance on obj , and passes along the specified parameters. If the method is static, the obj parameter is ignored. For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class.

Why we use invoke in C#?

Calling Invoke helps us because it allows a background thread to "do stuff" on a UI thread - it works because it doesn't directly call the method, rather it sends a Windows message that says "run this when you get the chance to".


1 Answers

You need to create the argument array first, and keep a reference to it. The out parameter value will then be stored in the array. So you can use:

object[] arguments = new object[] { "test", null }; MethodInfo method = ...; bool b = (bool) method.Invoke(null, arguments); byte[] rawAsm = (byte[]) arguments[1]; 

Note how you don't need to provide the value for the second argument, because it's an out parameter - the value will be set by the method. If it were a ref parameter (instead of out) then the initial value would be used - but the value in the array could still be replaced by the method.

Short but complete sample:

using System; using System.Reflection;  class Test {     static void Main()     {         object[] arguments = new object[1];         MethodInfo method = typeof(Test).GetMethod("SampleMethod");         method.Invoke(null, arguments);         Console.WriteLine(arguments[0]); // Prints Hello     }      public static void SampleMethod(out string text)     {         text = "Hello";     } } 
like image 116
Jon Skeet Avatar answered Sep 24 '22 15:09

Jon Skeet