Login Register






Dynamic API Declarations (ADVANCED) | VB & C# | Snippet filter_list
Author
Message
Dynamic API Declarations (ADVANCED) | VB & C# | Snippet #1
Yo.

So I was in need of some function to dynamically create API calls for things like WriteProcessMemory etc, it was originally intended for crypter use as you could easily decrypt the strings on runtime and no one would ever know that you're even using WinAPI calls on a static analysis. However this is for a different project, but this is completely custom, I only know of one other function similar to this and it's by Menalix, and I was originally using his, however, is didn't work for certain libraries like advapi32.dll so I just redid the entire thing.

THIS SHOULD WORK WITH ANY P.INVOKE(able) FUNCTION!

C#
IMPORTANT: YOU NEED TO IMPORT Microsoft.VisualBasic.dll TO USE Conversions.ToGenericParameter OR ELSE THIS WILL NOT WORK IN C#
Code:
public static T CreateAPI<T>(string wLib, string mName)        {            AssemblyBuilder ASMB = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(Assembly.GetExecutingAssembly().FullName), AssemblyBuilderAccess.RunAndSave);            ModuleBuilder MODB = ASMB.DefineDynamicModule(MethodBase.GetCurrentMethod().Name);            TypeBuilder TB = MODB.DefineType(MethodBase.GetCurrentMethod().DeclaringType.Name, TypeAttributes.Public);            MethodInfo MI = typeof(T).GetMethods()[0];            List<Type> LP = new List<Type>();            foreach (ParameterInfo pI in MI.GetParameters())                LP.Add(pI.ParameterType);            MethodBuilder MB = TB.DefinePInvokeMethod(mName,                                                      wLib,                                                      MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,                                                      CallingConventions.Standard,                                                      MI.ReturnType, LP.ToArray(),                                                      CallingConvention.Winapi,                                                      CharSet.Ansi);            MB.SetImplementationFlags(MB.GetMethodImplementationFlags() | MethodImplAttributes.PreserveSig);            return Conversions.ToGenericParameter<T>(Delegate.CreateDelegate(typeof(T), TB.CreateType().GetMethod(mName)));        }

C# USAGE:
In this case, I use GetCurrentHwProfileParameter, but you get the idea.
Code:
// Note: Return type and Parameters MUST BE CORRECT public delegate bool GetCurrentHwProfileParameter(IntPtr hw); public static GetCurrentHwProfileParameter GetCurrentHwProfile; GetCurrentHwProfile = CreateAPI<GetCurrentHwProfileParameter>("advapi32.dll", "GetCurrentHwProfile"); //Cast the Delegate GetCurrentHwProfile(lHWInfoPtr); //Now you can call it like a normal function!

VB.Net
Code:
Public Shared Function CreateAPI(Of T)(wLib As String, mName As String) As T Dim ASMB As AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(New AssemblyName(Assembly.GetExecutingAssembly().FullName), AssemblyBuilderAccess.RunAndSave) Dim MODB As ModuleBuilder = ASMB.DefineDynamicModule(MethodBase.GetCurrentMethod().Name) Dim TB As TypeBuilder = MODB.DefineType(MethodBase.GetCurrentMethod().DeclaringType.Name, TypeAttributes.[Public]) Dim MI As MethodInfo = GetType(T).GetMethods()(0) Dim LP As New List(Of Type)() For Each pI As ParameterInfo In MI.GetParameters() LP.Add(pI.ParameterType) Next Dim MB As MethodBuilder = TB.DefinePInvokeMethod(mName, wLib, MethodAttributes.[Public] Or MethodAttributes.[Static] Or MethodAttributes.PinvokeImpl, CallingConventions.Standard, MI.ReturnType, LP.ToArray(), _ CallingConvention.Winapi, CharSet.Ansi) MB.SetImplementationFlags(MB.GetMethodImplementationFlags() Or MethodImplAttributes.PreserveSig) Return Conversions.ToGenericParameter(Of T)([Delegate].CreateDelegate(GetType(T), TB.CreateType().GetMethod(mName))) End Function
VB.Net USAGE:
See C# Usage, it's not that hard to convert.

Enjoy folks, I think I could handle the array conversion a little better and maybe even inline, but I'm too lazy to LINQ it.


[+] 1 user Likes Killpot's post
Reply

RE: Dynamic API Declarations (ADVANCED) | VB & C# | Snippet #2
Just so you know, what you're doing with Conversions.ToGenericParameter can be done without the need for the VisualBasic reference... Why not just this:
Code:
public static T GenericDelegateCast<T>(Delegate obj) { return (T)((object)obj); }

You're not casting to primitive types that may require more than just a cast; a specific conversion. You can cast object to type T. Including Microsoft.VisualBasic.dll is not worth it.

Code:
return GenericDelegateCast<T>(Delegate.CreateDelegate(typeof(T), TB.CreateType().GetMethod(mName)));

Or if you wanted to avoid the function call:
Code:
return (T)((object)Delegate.CreateDelegate(typeof(T), TB.CreateType().GetMethod(mName)));

Conversions.ToGenericParameter is definitely not the right function for this task however because most of what it does is with primitive value types, not the Delegate type.

One thing that always got me is why in the world MethodImplAttributes was never marked with the FlagsAttribute... Seems like it was overlooked to me. There are modifications that it makes to inherited System.Object functions like ToString() but it really doesn't seem relevant.

[+] 1 user Likes 0xDEAD10CC's post
Reply

RE: Dynamic API Declarations (ADVANCED) | VB & C# | Snippet #3
(08-01-2016, 12:39 AM)0xDEAD10CC Wrote: Just so you know, what you're doing with Conversions.ToGenericParameter can be done without the need for the VisualBasic reference... Why not just this:
Code:
public static T GenericDelegateCast<T>(Delegate obj) {    return (T)((object)obj); }

You're not casting to primitive types that may require more than just a cast; a specific conversion. You can cast object to type T. Including Microsoft.VisualBasic.dll is not worth it.

Code:
return GenericDelegateCast<T>(Delegate.CreateDelegate(typeof(T), TB.CreateType().GetMethod(mName)));

Or if you wanted to avoid the function call:
Code:
return (T)((object)Delegate.CreateDelegate(typeof(T), TB.CreateType().GetMethod(mName)));

Conversions.ToGenericParameter is definitely not the right function for this task however because most of what it does is with primitive value types, not the Delegate type.

One thing that always got me is why in the world MethodImplAttributes was never marked with the FlagsAttribute... Seems like it was overlooked to me. There are modifications that it makes to inherited System.Object functions like ToString() but it really doesn't seem relevant.

Thanks for the info man, I scraped that part from Menalix's version and didn't even try to see if it was the most efficient way, It seemed really bulky and I wasn't a fan, thanks for the info!


Reply