Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the purpose of the __thiscall keyword?

Tags:

c++

visual-c++

When reading through the calling conventions there is a thiscall convention which purpose is pretty clear.

I understand that thiscall defines a function which is part of a class, because these functions require an object as their first hidden parameter for non-static functions.

So if I understand it right, then the following function have to be thiscall. The keyword doesn't need to be used because the compiler doesn't have much choice there and have to declare it as such.

 class Foo
 {
     public:
     int function(void) { return 1; }
 };

Now when I declare functions outside a class like this:

int __thiscall Otherfunction(void) { return 1; }
int __thiscall Otherfunction(Foo *t) { return 1; }

Then I get the compiler error:

error C3865: '__thiscall': can only be used on native member functions

It even makes sense because how would you call these functions? So why does this keyword even exist if it can not be used? Or is there some usecase where this can/has to be used?

like image 587
Devolus Avatar asked Sep 02 '25 01:09

Devolus


1 Answers

From the official __thiscall documentation.

On ARM, ARM64, and x64 machines, __thiscall is accepted and ignored by the compiler. That's because they use a register-based calling convention by default.

One reason to use __thiscall is in classes whose member functions use __clrcall by default. In that case, you can use __thiscall to make individual member functions callable from native code.

When compiling with /clr:pure, all functions and function pointers are __clrcall unless specified otherwise. The /clr:pure and /clr:safe compiler options are deprecated in Visual Studio 2015 and unsupported in Visual Studio 2017.

This appears to imply that __thiscall is never required to be explicitly specified when writing plain C++ (unmanaged) code on ARM[64] or x86, or C++/CLI code in VC++ versions 2017 and later.

like image 107
dxiv Avatar answered Sep 13 '25 11:09

dxiv