digitalmars.D.learn - Interfacing to const T& or const T* C++ code
- Atila Neves (24/24) Jun 01 2014 So I was mucking about with calling C++ from D yesterday and was
- bearophile (6/12) Jun 01 2014 This doesn't look very safe because D const is transitive, unlike
- Atila Neves (7/21) Jun 02 2014 Oh, it's not even remotely safe and I know that. But it's "kinda"
- Kagamin (1/1) Jun 02 2014 Try to report as a bug.
So I was mucking about with calling C++ from D yesterday and was pleasantly surprised that this worked: D: struct Foo { int i; int j; } extern(C++) void useFoo(ref const(Foo) foo); C++: struct Foo { int i; int j; }; void useFoo(const Foo& foo) { ... } In fact, omitting const on either side causes a link error, and the same for using a pointer instead of a reference on one of the sides. All good. But this doesn't work: D: extern(C++) interface DClass { int getIndex() const; } extern(C++) void useObj(in DClass dclass); //I also tried const(DClass) C++: struct DClass { virtual int getIndex() const = 0; } void useObj(const DClass* dclass); //DClass* works though! I can make `DClass` `const` or `in` in D as much as I want, but it fails to link if I add const on the C++ side. Is there a reason why it works for structs (as it should) but not classes? It'd be nice to be able to pass classes in by const T&. Or even const T*! Atila
Jun 01 2014
Atila Neves:D: struct Foo { int i; int j; } extern(C++) void useFoo(ref const(Foo) foo); C++: struct Foo { int i; int j; }; void useFoo(const Foo& foo) { ... }This doesn't look very safe because D const is transitive, unlike the C++ const. So in the C++ code you can mutate inner data inside foo and the D code will assume such data is not changed. Bye, bearophile
Jun 01 2014
On Sunday, 1 June 2014 at 09:18:50 UTC, bearophile wrote:Atila Neves:Oh, it's not even remotely safe and I know that. But it's "kinda" safe and it "works" for structs, so why not classes? The worse thing about this is that I can happily slap a "const" in the D declaration and it'll link to non-const C++ code. That's a lot less safe than treating C++ const as if it were D const. AtilaD: struct Foo { int i; int j; } extern(C++) void useFoo(ref const(Foo) foo); C++: struct Foo { int i; int j; }; void useFoo(const Foo& foo) { ... }This doesn't look very safe because D const is transitive, unlike the C++ const. So in the C++ code you can mutate inner data inside foo and the D code will assume such data is not changed. Bye, bearophile
Jun 02 2014