Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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});
like image 814
Remko Avatar asked Aug 21 '12 20:08

Remko


People also ask

How do you call a function inside a class?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

Can you call a method from another class in C#?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.

Can internal class have public methods?

The short answer is that it doesn't matter. Public methods of an internal class are internal. To the compiler, the internal/public method distinction only matters for public classes.


2 Answers

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);
like image 51
Mike Zboray Avatar answered Sep 30 '22 06:09

Mike Zboray


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.

like image 33
Alexei Levenkov Avatar answered Sep 30 '22 04:09

Alexei Levenkov