Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
4.00/5 (3 votes)
See more:
I have the following problem which Im simplifying in small methods rather than defining the whole real problem I have.

MathLibrary.dll -->> saved at C:\MyApplications

C#
namespace Math
{
     public class SimpleMath
     {
          public int Add(int a, int b)
          {
              return a + b;
          }
     }
}

I want to invoke in another application:

namespace OtherApp
{
     class Program
     {
          static void Main()
          {
               Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               int sum = m.Invoke(obj,new object[]{10, 20});
          }
     }
}


But what if the Add method was defined as so:
C#
public void Add(int a, int b, out int sum)


How could I invoke the method?
Thanks
Posted
Updated 7-Mar-12 8:42am
v3

1 solution

You invoke it like any other method through reflection. except that the returned value will be copied back into the parameter array so you can access it from the calling function.

Eg;

C#
class Program
     {
        delegate int Run(int a, int b, out int sum);
         private static Run invoke;           

          static void Main()
          {
               Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               invoke = (Run)Delegate.CreateDelegate(typeof(Run), obj, m);
               // call invoke.
               int sum;
               sum = invoke(10, 20, out sum);
          }
     }


Or you can try this
C#
Assembly asm = Assembly.LoadFrom(@"C:\MyApplications\MathLibrary.dll");
               Type simpleMath = asm.GetType("MathLibrary.SimpleMath");
               object obj = Activator.CreateInstance(simpleMath);
               MethodInfo m = simpleMath.GetMethod("Add");
               int sum;
               sum = m.Invoke(obj,new object[]{10, 20, sum});


Please vote and mark as solution if this solves your problem thanks.
 
Share this answer
 
Comments
Wonde Tadesse 7-Mar-12 22:44pm    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900