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});
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With