Friday, March 30, 2012

Pass pointer as parameter to method invoked using reflection

Recently, I was trying to execute one of the CLR internal private static method declared in System.Math class. This method excepts double pointer but Method.Invoke accepts object array and double pointer cannot be type as object.

Background:
I wanted to customize rounding functionality of double. So I used reflector and identified the code used for rounding. This code uses CLR internal SplitFractionDouble method that can return splitted decimal part and removes the decimal part from the value at double pointer passed as parameter. So in my custom logic I wanted to call that method but the problem is how to pass double pointer as object in the Invoke method. Following are the steps to resolve that issue and was able to call the method successfully.

1. Start unsafe block or add the logic in unsafe function

2. Getting method info of CLR internal method. Here parameter type is added as a typeoff(double*).
MethodInfo methodInfo = typeof(Math).GetMethod("SplitFractionDouble", BindingFlags.NonPublic | BindingFlags.Static, Type.DefaultBinder,new[] { typeof(double*) },null);

3. Call the method. Here most important thing is that address of value is typecasted into int and then further type casted into IntPtr. IntPtr can be used for any kind of references.
 var result = (double)methodInfo.Invoke(null, new object[] { (IntPtr)(int)&value});

No comments:

Post a Comment