Remko
Remko

Reputation: 7330

Calling an function inside an internal class from an another executable

I want to call a function from a .net executable from my own code. I used reflector and saw this:

namespace TheExe.Core
{
    internal static class AssemblyInfo
    internal static class StringExtensionMethods
}

In namespace TheExe.Core is the function I am interested in:

internal static class StringExtensionMethods
{
    // Methods
    public static string Hash(this string original, string password);
    // More methods...
}

Using this code I can see the Hash Method but how do I call it?

Assembly ass = Assembly.LoadFile("TheExe");
Type asmType = ass.GetType("TheExe.Core.StringExtensionMethods");
MethodInfo mi = asmType.GetMethod("Hash", BindingFlags.Public | BindingFlags.Static);
string[] parameters = { "blabla", "MyPassword" };

// This line gives System.Reflection.TargetParameterCountException
// and how to cast the result to string ?
mi.Invoke(null, new Object[] {parameters});

Upvotes: 8

Views: 12677

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

If you need this for testing purposes consider using InternalsVisibleTo attribute. This way you can make your test assembly to be "friend" of main assembly and call internal methods/classes.

If you don't have control (or can't sign) assemblies - reflection is the way to do it if you have to. Calling internal methods of third party assemblies is good way to get headaches when that assembly changes in any shape of form.

Upvotes: 3

Mike Zboray
Mike Zboray

Reputation: 40818

You are passing an array of strings as a single parameter with your current code.

Since string[] can be coerced to object[], you can just pass the parameters array into Invoke.

string result = (string)mi.Invoke(null, parameters);

Upvotes: 9

Related Questions