Re: Some form of __thiscall support

  • From: Mike Pall <mike-1206@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 29 Jun 2012 10:57:06 +0200

I wrote:
> Claire Lewis wrote:
> > It would be pretty handy to have some sort of support for
> > marking functions as “__thiscall” calling convention (or
> > equivalent), such that one could directly use the decorated C++
> > names, passing ‘this’ as the first argument.
> Actually, the __thiscall declaration already works. But the call
> setup is still wrong.

Umm, I was wrong. It's already implemented correctly. I just never
bothered to actually try it ... :-)

Here's some sample C++ code:

  class __declspec(dllexport) Foo {
    Foo(int a);
    int get();
    int x;
  Foo::Foo(int a) { x = a; }
  int Foo::get() { return x; }

Compile that into test.dll with MSVC on Windows/x86.

Then run the C++ code with this Lua program:

  local ffi = require("ffi")
  typedef struct { int x; } Foo;
  Foo * __thiscall Foo_new(Foo *, int) asm("??0Foo@@QAE@H@Z");
  int __thiscall Foo_get(Foo *) asm("?get@Foo@@QAEHXZ");
  local lib = ffi.load("a.dll")
  local foo ="Foo")
  lib.Foo_new(foo, 42)

The name mangling is specific to MSVC and x86. The mangled names
for x64 are "??0Foo@@QEAA@H@Z" and "?get@Foo@@QEAAHXZ". GCC has
its own C++ name mangling scheme.

Note: __thiscall is only needed for C++ methods compiled with MSVC
on Windows/x86. Windows/x64 has a unified calling convention. GCC
doesn't use __thiscall, even on Windows/x86.


Other related posts: