Dynamic API Calls in .NET
2 minute read Published:
Using Reflection to call APIs dinamically
Today I’m going to share a way to call APIs without DLLImport. I’ve first saw this years ago at OpenSC.ws as far as I remember and got into the idea. The code was lost since then but I found a copy.
Program.cs
using System;
using System.Reflection;
namespace APICaller
{
class Program
{
```
public static void Main(string[] args)
{
Console.Title = "Dynamic API Caller";
Console.WriteLine("Press any key to call your API!");
Console.ReadKey(true);
string className = MethodBase.GetCurrentMethod().DeclaringType.Name; //getting our current class name
string asmName = Assembly.GetExecutingAssembly().FullName; //getting our current assembly name
string methodName = MethodBase.GetCurrentMethod().Name; //getting our current method name
//Sample with a simple MessageBox. You can adapt this call to whatever you need
//(note that you should also adapt the class if needed)
DynamicAPIs CreateDynamicAPI = new DynamicAPIs("user32.dll",
"MessageBoxA",
asmName,
methodName,
className,
typeof(int),
new object[] {
IntPtr.Zero,
"Test Message",
"Test Title",
0
});
Console.Write("Press any key to exit . . . ");
Console.ReadKey(true);
}
}
```
}And our mighty class.