Hello HF :)
Today i'm gonna show you this code, it automatically generates delegate types with Reflection.Emit.
So
This is the constructor of the invoker class.
It generates a dynamic assembly.
This is the start of the code, T is a generic type definited when calling the method.
The function accept :
Firstly it loads the library and check for errors
Then it gets the function address and check for errors.
after it creates parameter type array for constructing the delegate.
Then it creates the delegate using TypeBuilder.
Example Code :
To see the full code go to my blog : frontenhack.me
Today i'm gonna show you this code, it automatically generates delegate types with Reflection.Emit.
So
Code
public DynamicDelegateApiInvoker()
{
AssemblyName assembly = new AssemblyName();
assembly.Version = new Version(1, 0, 0, 0);
assembly.Name = "ReflectionEmitDelegate";
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);
}It generates a dynamic assembly.
Code
public T InvokeApi<T>(string library, string function, object[] parameters)
{
IntPtr hModule = LoadLibrary(library);
if (hModule == IntPtr.Zero) return default(T);
IntPtr hHandle = GetProcAddress(hModule, function);
if (hHandle == IntPtr.Zero) return default(T);
Type[] parameterTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
parameterTypes[i] = parameters[i].GetType();The function accept :
- the library name (Ex. "user32.dll")
- the function name (Ex. "MessageBoxA")
- the parameters (Ex. new object[] {IntPtr.Zero, "Hello", "Buddy", 0})
Firstly it loads the library and check for errors
Then it gets the function address and check for errors.
after it creates parameter type array for constructing the delegate.
Then it creates the delegate using TypeBuilder.
Example Code :
Code
class Program
{
static void Main(string[] args)
{
DynamicDelegateApiInvoker api = new DynamicDelegateApiInvoker();
api.InvokeApi<int>("user32.dll", "MessageBoxA", new object[] {IntPtr.Zero, "Hello", "Buddy", 0});
Process.GetCurrentProcess().WaitForExit();
}
}To see the full code go to my blog : frontenhack.me


![[Image: jfhDhRz.gif]](https://i.imgur.com/jfhDhRz.gif)

