c++ 动态设置函数

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>

using namespace std;

typedef int(__stdcall* FUN1)();

FUN1 fun1;

int main()
{
	BYTE* newmem = (BYTE*)VirtualAlloc(0, 100, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	BYTE bytes[] = {
		0xB8, 0x0A, 0x00, 0x00, 0x00, // mov eax, 0xa
		0xC3,			      // ret
	};
	int len = sizeof(bytes);
	memcpy_s(newmem, len, bytes, len);
	fun1 = (FUN1)newmem;

	cout << fun1() << endl; // 10
	VirtualFree(newmem, 0, MEM_RELEASE);
	return 0;
}
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>

using namespace std;

typedef int(__stdcall* FUN1)();

FUN1 fun1;

void setFun(uintptr_t* fun)
{
	BYTE* newmem = (BYTE*)VirtualAlloc(0, 100, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	BYTE bytes[] = {
		0xB8, 0x0A, 0x00, 0x00, 0x00, // mov eax, 0xa
		0xC3,			      // ret
	};
	int len = sizeof(bytes);
	memcpy_s(newmem, len, bytes, len);
	*fun = (uintptr_t)newmem;
}

int main()
{
	setFun((uintptr_t*)&fun1);
	cout << fun1() << endl; // 10
	return 0;
}
原文地址:https://www.cnblogs.com/ajanuw/p/13457513.html