function pointer bug?

ketmar via Digitalmars-d digitalmars-d at puremagic.com
Mon Oct 27 17:20:13 PDT 2014


On Mon, 27 Oct 2014 23:52:38 +0000
bitwise via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> The code below suggests the latter, although it doesn't 
> explicitly state it:
> 
> static addr = &TestClass.instanceMethod;
> Error: non-constant expression & instanceMethod
> 
> I may be missing a subtle difference, but in C++, this code works:
> 
> class TestAddr {
>      public: virtual void test() { cout << "test" << endl; }
> };
> 
> int main(int argc, const char * argv[])
> {
>      TestAddr test;
>      static auto ptr = &TestAddr::test;
>      (test.*ptr)();
>      return 0;
> }
C++ compiler does some trickery behind the curtains. besides, you
aren't supposed to make such hackish things easily in D. yet you can:

  class TestClass {
    int n = 42;
    void test() { writeln("test: ", n); }
  }

  void main () {
    auto test = new TestClass();
    void delegate () a;
    {
      a.ptr = *cast(void**)&test; // protection from opCast()
        // this can be done as `cast(void*)test;` too
      enum idx = __traits(getVirtualIndex, TestClass.test);
      a.funcptr = cast(void function())TestClass.classinfo.vtbl[idx];
      a(); // outputs 'test: 42'
    }
  }


you need to manually create initialization code that C++ compilers
creates behind the curtains. if you aren't in urgent need of that code,
may i suggest you to read D books and D specs? D is not C++, and D
delegates aren't C++ member function pointers (yet they works nearly
the same).

this is kind of advanced topic, and i don't think that dumping
working source code at you will help without you grasp the low-level
mechanics first.

besides, you can use CTFE to build wrapper code. Adam Ruppe has that in
his jsvar.d, and i have that in my cong.d (cmdcon-ng) too.

not that i'm not willing to help you, but i can't see what you
understand and what not, so i don't know where i should start
explaining.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20141028/99ada544/attachment.sig>


More information about the Digitalmars-d mailing list