Skip to content

Instantly share code, notes, and snippets.

@MikuAuahDark
Created July 25, 2020 04:45
Show Gist options
  • Save MikuAuahDark/23b4d93cee8bed7f9188dd0d7128d6f0 to your computer and use it in GitHub Desktop.
Save MikuAuahDark/23b4d93cee8bed7f9188dd0d7128d6f0 to your computer and use it in GitHub Desktop.
MinGW-w64 32-bit __thiscall test
/*
Using MSVC toolchain, compile this as follows
$ clang.exe -target i386-pc-windows-msvc -shared -o dummy.dll dummy.cpp
*/
#include <cstdio>
struct __declspec(dllexport) DummyBase
{
int someValue;
virtual int someMethod()
{
printf("Class DummyBase. My this pointer is %p\n", this);
return someValue;
}
};
struct __declspec(dllexport) DummyDerived: public DummyBase
{
int someMethod() override
{
printf("Class DummyDerived. My this pointer is %p\n", this);
return someValue;
}
virtual int someMethod2(int avalue)
{
printf("Class DummyDerived. avalue = %d, this = %p\n", avalue, this);
return someMethod();
}
};
extern "C"
{
__declspec(dllexport) void *newDummyDerived(int v)
{
DummyDerived *a = new DummyDerived;
a->someValue = v;
return a;
}
}
/*
Assume you have GCC (MinGW-w64 32-bit) and MSVC toolchain, compile as follows
$ clang.exe -target i386-pc-windows-msvc -o a_msvc.exe main.cpp -ldummy
$ clang.exe -target i686-w64-mingw32 -o a_gcc.exe main.cpp dummy.lib
Then run a_msvc.exe and a_gcc.exe
*/
#include <cstdio>
extern "C" void *newDummyDerived(int v);
int callDummyDerivedSomeMethod2(void *a, int avalue)
{
using SomeMethod2Func = int(__thiscall *)(void*, int);
printf("callDummyDerivedSomeMethod2. avalue = %d, this = %p\n", avalue, a);
// Access vtable directly
SomeMethod2Func someMethod2 = (* ((SomeMethod2Func**) a))[1];
return someMethod2(a, avalue);
}
int main()
{
void *dummyDerived = newDummyDerived(12345);
printf("someMethod2 = %d\n", callDummyDerivedSomeMethod2(dummyDerived, 67890));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment