Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling ILAsm global function from C# code

Tags:

c#

.net

clr

ilasm

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?

like image 236
user2341923 Avatar asked Sep 03 '25 09:09

user2341923


2 Answers

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.
like image 59
Simon Whitehead Avatar answered Sep 05 '25 01:09

Simon Whitehead


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.

like image 39
Jon Skeet Avatar answered Sep 05 '25 00:09

Jon Skeet