Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void BindNative(IntPtr functionPtr, String name, String prototype)
- {
- /*
- * Manual implementation of a __cdecl function calling a __fastcall function.
- * 1. Allocate Executable memory.
- * 2. Write the function.
- * 3. Call the function.
- * 4. Release allocated memory.
- * TODO: Improve this to a more static function.
- * push, prototype string pointer
- * mov edx, name string pointer
- * mov ecx, function pointer
- * call, BindNative pointer; Remember to calculate the relative offset
- * retn
- */
- var code = new Byte[21];
- using (var writer = new AssemblyWriter(new MemoryStream(code)))
- {
- var codePtr = Kernel32.VirtualAlloc(IntPtr.Zero, code.Length, AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
- writer.Write(Assembly.PushLV, prototype);
- writer.Write(Assembly.MoveEDX, name);
- writer.Write(Assembly.MoveECX, functionPtr);
- writer.Write(Assembly.Call, (UInt32)bindNativePtr - (UInt32)codePtr - (UInt32)writer.BaseStream.Position - 5u); // -5u is to get back to the start of the call instruction, 5 is the size of the instruction.
- writer.Write(Assembly.Return);
- Marshal.Copy(code, 0, codePtr, code.Length);
- var bindNative = (BindNativePrototype)Marshal.GetDelegateForFunctionPointer(codePtr, typeof(BindNativePrototype));
- bindNative();
- Kernel32.VirtualFree(codePtr, code.Length, MemoryFreeType.Release);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment