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.GetTypes()[0].GetMethod("test", BindingFlags.Static | BindingFlags.NonPublic);
bool b = (bool)_lf.Invoke(null, new object[]
{
"test",
rawAsm
});
The bytes returned are null.
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: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 aref
parameter (instead ofout
) then the initial value would be used - but the value in the array could still be replaced by the method.Short but complete sample:
When a method invoked by reflection has a
ref
parameter it will be copied back into the array that was used as an argument list. So to get the copied back reference you simply need to look at the array used as arguments.After this call
args[1]
will have the newbyte[]