Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically calling a dll and method with arguments

Basically I'm trying to call a dll by name, instantiate an object, then call a method by name in that dll. I'm getting an "Exception has been thrown by the target of an invocation." during the Method.Invoke. I'm fairly sure my problem is with the typecasting of the arguments of the method. I was wondering if anyone had any input on this exception. Additionally, any suggestions on how to revise my approach are welcome.

public void calldll(string dllName, string typeName, string methodName, string arguments) {

    string[] argumentArray = arguments.Split(new char[] { '|' }, StringSplitOptions.None);

    Assembly assembly = Assembly.LoadFrom(dllName);
    System.Type type = assembly.GetType(typeName);
    Object o = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName);
    ParameterInfo[] parameters = method.GetParameters();

    object[] methodParameters = new object[parameters.GetLength(0)];

    for (int i = 0; i < parameters.Length - 1; i++)
    {
        var converter = TypeDescriptor.GetConverter(parameters[i].GetType());
        methodParameters[i] = converter.ConvertFrom(argumentArray[i]);
    }

    method.Invoke(o, methodParameters); }
like image 793
crlanglois Avatar asked Aug 09 '12 15:08

crlanglois


1 Answers

I found two issues with your code:

  1. You are not looping over all parameters. You should remove -1 from the for loop.
  2. When you are creating your converter, you call the GetType() method. This returns the Type of the ParameterInfo object, not the Type of the parameter. Use the property ParameterType instead.

All in all, change the first lines in the for loop to this:

for (int i = 0; i < parameters.Length; i++)
{
   var converter = TypeDescriptor.GetConverter(parameters[i].ParameterType);

Once you have done these corrections, I believe your code should run as intended. At least it did for me when I tested a simple void Hello(int x, string y) method.

like image 67
Anders Gustafsson Avatar answered Nov 11 '22 23:11

Anders Gustafsson