How to pass a class by (const) reference to C++

evilrat evilrat666 at gmail.com
Mon Dec 13 12:51:17 UTC 2021


On Monday, 13 December 2021 at 12:16:03 UTC, Ola Fosheim Grøstad 
wrote:
> On Monday, 13 December 2021 at 12:08:30 UTC, evilrat wrote:
>> Yeah but it sucks to have making C++ wrapper just for this. I 
>> think either pragma mangle to hammer it in place or helper 
>> dummy struct with class layout that mimics this shim logic is 
>> a better solution in such cases.
>> Literally anything but building C++ code twice for a project.
>
> Does something like this work?
>
>
> ```
> class _A {}
> struct A {}
>
> extern(C++) void CppFunc(ref const(A) arg);
>
> void func(_A a){
>     CppFunc(*cast(A*)a);
> }
> ```

Only if this struct matches class memory layout, the only 
potential problem is ctor on C++ side.
Also C++ class will likely be NOT zero initialized and have byte 
gaps due to alignment, this can mess up many things including 
(default) equality operators and such.

That example is still looks very conspicuous because it is very 
likely does nothing on the caller side in C++ as it passes a 
copy. Such things may indicate that the library author have no 
idea what he is doing, and it works on occasion.

All this will require extra care or it will explode in your face, 
and is quite hard to debug without such low-level knowledge of 
details.


More information about the Digitalmars-d-learn mailing list