This is very similar to issue #11175, and can be solved in the same way.
The gist of it is that when an interface does not support toString, it is cast to Object to call toString. If casting to object does not work, it simply prints null.
Well, we can print at least the address of the object if toString is not supported.
One issue is that it's a little difficult to unit-test this. You need a C++ object, and there is no way to create it in D. From my attempts, I can't even *cast* a void * pointer to a C++ interface. The compiler doesn't seem to allow any type of casting to C++ interfaces (bug?).
Here is the only way I was able to get it to test:
module cppcast;
// need to circumvent mangling
extern(C) void *cppcast(void *ptr)
{
return ptr;
}
module testcppcast;
version(unittest)
{
extern(C++) interface X
{
}
extern(C) X cppcast(void *ptr);
}
unittest
{
auto dummy = cast(void*)1234;
auto x = cppcast(dummy); // dummy c++ class, doesn't need to be valid
string expected = format("%X", dummy);
formatTest(x, expected); // fails, x is printed as 'null'
}
Special-casing C++ interfaces to cast to void * if they don't have a toString method should work, just like the IUnknown solution.
Comment #1 by yebblies — 2014-04-24T16:59:38Z
The requested example of how to create classes usable through extern(C++) interfaces - pretty much how you'd expect.
import std.stdio;
extern(C++)
interface I
{
void fun();
}
extern(C++)
class C : I
{
void fun() { writeln("This works..."); }
}
class D : I
{
extern(C++):
void fun() { writeln("And so does this!"); }
}
void main()
{
I i = new C();
i.fun();
i = new D();
i.fun();
}
Comment #2 by schveiguy — 2014-04-24T18:03:47Z
Thanks.
An updated unit test:
version(unittest)
{
extern(C++) interface X
{
}
extern(C++) class C : X
{
}
}
unittest
{
X x = new C;
string expected = format("%X", cast(void *)x);
formatTest(x, expected); // fails, x is printed as 'null'
}
@yebblies While fiddling around, I found an issue with extern(C++) classes (not related to this). See issue #12636
Comment #3 by robert.schadek — 2024-12-01T16:20:51Z