#23 - Function in user allocated memory

Data: 2018-08-25 12:00 - C++

Copies an existing function to a user allocated memory space and run a function from it.

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

typedef int(*binaryFunc)(int, int);

int sum(int a, int b) {
	return a + b;
}
void sumEnd() { }

void* copyFunc(void* funcStart, void* funcEnd) {
	int funcSize = (int)funcEnd - (int)funcStart;
	void* func = VirtualAlloc(NULL, funcSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	memcpy(func, funcStart, funcSize);
	return func;
}

int main() {
	binaryFunc sumFunc = (binaryFunc)copyFunc(&sum, &sumEnd);

	std::cout << sumFunc(10, 20);
	std::cin.get();
}

Previous snippet | Next snippet