On Saturday, 8 November 2025 at 10:04:45 UTC, user1234 wrote:
Following recent discussion in the General group, I had the idea to use `opCast` in order to return a specially cooked interface instance.

That would not be a decent solution because for example `opCast` template func is not virtual but nonetheless I'd like to know if this could work...

Only problem is that I cant manage to build the custom interface, or more exactly, it is not binary compatible:

Slightly less C-ish and eliminating the recursive opCast, but still not working (valgrind reports memory errors)

```d
import core.stdc.stdio, core.memory;

interface CanStart
{
    void start();
}

class Base : CanStart
{
    public void start()
    {
        puts("object start()");
    }

    public void interfaceStart()
    {
        puts("itf start()");
    }

    T opCast(T)()
    {
        static if (is(T == CanStart))
        {
            struct S
            {
                Base b;
                void* f;
            }

            auto s = cast(S*) GC.malloc(size_t.sizeof*2);
            s.b = this;  // likely the issue
            s.f = (&interfaceStart).ptr;

            auto result = *cast(CanStart*) s;

            return result;
        }
        assert(0);
    }
}

void main()
{
    auto b = new Base;
    b.start();

    auto cs = cast(CanStart) b;
    cs.start();
}
```

Anyone ?
  • Struggling tryin... user1234 via Digitalmars-d-learn
    • Re: Struggl... user1234 via Digitalmars-d-learn
    • Re: Struggl... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Reply via email to