在C++中如何动态创建一个函数

来源:百度知道 编辑:UC知道 时间:2024/06/18 02:21:24
在堆中分配内存给函数,在调用时会发生异常。
那么怎么动态创建函数?

#include <cstdlib>
int main()
{
void(*c)() = (void(*)())malloc(1);
*(unsigned char*)c = 0xC3; // ret
c(); // raise Excpetion 0xC0000005: Access violation
free(c);
}
数据执行保护也来找我程序的麻烦了……
有办法绕过保护机制调用吗?

BOOL VirtualProtect(
LPVOID lpAddress, // address of region of committed pages
DWORD dwSize, // size of the region
DWORD flNewProtect, // desired access protection
PDWORD lpflOldProtect
// address of variable to get old protection
);
或者WriteProcessMemory(...

但是如果你发生了内存不能执行的话 你可以用这个API改变内存的属性
更直接得 你可以使用VirtualAlloc 它申请的内存可以直接设置读写执行.

#include <cstdlib>
#include <windows.h>

int main()
{
MessageBox(NULL, "我不是真的调用.", NULL, MB_OK);

char szFunText[] = {0x6A, 0x00, 0x6A, 0x00, 0x6A, 0x00, 0x6A, 0x00, 0xB8, 0x8A, 0x05, 0xD5, 0x77, 0xFF, 0xD0, 0xC3};

//PAGE_EXECUTE_READWRITE 可读可写可执行
PVOID pMem = VirtualAlloc(NULL, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(pMem, szFunText, sizeof(szFunText));
((void(*)())pMem)();
VirtualFree(pMem, 1024, MEM_RELEASE);

return 0;
}