Created
August 19, 2015 09:32
-
-
Save vittee/bb3ff2bf7ccf30ded719 to your computer and use it in GitHub Desktop.
Calling C++ method using function pointer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
#include <stdlib.h> | |
class MyClass { | |
private: | |
int val = 0; | |
public: | |
MyClass(int i) { | |
val = i; | |
} | |
virtual int test(int a); | |
}; | |
typedef int(__thiscall *myclass_test)(void* pThis, int a); | |
int MyClass::test(int a) | |
{ | |
return a * 2 + val; | |
} | |
uintptr_t get_myclass_test_addr() { | |
char buffer[256]; | |
sprintf_s(buffer, "%d", &MyClass::test); | |
return (uintptr_t) _atoi64(buffer); | |
} | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
uintptr_t ptr_func = get_myclass_test_addr(); | |
MyClass *inst = new MyClass(5); | |
myclass_test test_method = (myclass_test)ptr_func; | |
int result = test_method(inst, 10); | |
printf_s("result = %d", result); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment