Question

Suppose I have an ILAsm library with the following code:

.assembly extern mscorlib{}
.assembly TestMe{}
.module TestMe.dll
.method public static void PrintMe() cil managed 
{
    ldstr "I'm alive!"
    call void [mscorlib]System.Console::WriteLine(string)
    ret
}

How can I call a global PrintMe() function from a C# code?

Was it helpful?

Solution

You can via reflection.. but not in any really useful way:

var module = Assembly.LoadFile("path_to_dll.dll").GetModules()[0]; 
// the first and only module in your assembly
var method = module.GetMethod("PrintMe");

method.Invoke(null, 
              BindingFlags.Public | BindingFlags.Static, 
              null, 
              null, 
              CultureInfo.CurrentCulture); // Prints "I'm alive!" to console.

OTHER TIPS

You can't, as far as I'm aware. C# only "knows" about methods declared in types - not at the top level. Move your method into a type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top