How to pass a class by (const) reference to C++
Tejas
notrealemail at gmail.com
Tue Dec 14 06:21:39 UTC 2021
On Monday, 13 December 2021 at 12:08:30 UTC, evilrat wrote:
> On Monday, 13 December 2021 at 11:13:12 UTC, Tejas wrote:
>> On Monday, 13 December 2021 at 09:21:26 UTC, Jan wrote:
>>> [...]
>>
>> You'll have to use something called a
>> [shim](https://en.wikipedia.org/wiki/Shim_(computing)), it
>> seems.
>>
>> For example:
>>
>> `main.d` :
>>
>> ```d
>>
>> extern(C++) class A{}
>>
>> extern(C++) void cppFunc_shim(A arg);
>>
>> void main(){
>> A a = new A();
>> cppFunc_shim(a);
>> }
>>
>> ```
>>
>> `cppShim.cpp` :
>>
>> ```c++
>>
>> class A{};
>>
>> extern void cppFunc(A const &arg);
>>
>> void cppFunc_shim(A *param){
>> const A forwardingVar = A(*param);
>> cppFunc(forwardingVar);
>> }
>>
>> ```
>>
>> `cppFunc.cpp` :
>>
>> ```c++
>>
>> #include "iostream"
>> class A{};
>>
>> void cppFunc(A const &arg){
>> //std::cout << arg << std::endl;
>> std::cout << "Called cppFunc :D" << std::endl;
>> }
>>
>> ```
>>
>> Then pass the following on the command line(assuming all files
>> are in the same directory):
>>
>> `ldmd2 main.d cppFunc.o cppShim.o -L-lstdc++`
>>
>> That's what it took to make it work for me, dunno if more
>> convenient methods exist.
>>
>> Hope it helps :D
>
> 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.
Hey, evilrat, I've seen people make claims that our C++ interop
has reached phenomenal levels and that going any further would
basically require a C++ compiler ala ImportC++, the issue is just
that the docs haven't been updated yet to reflect it.
What do you think about this? Is this really true? Because it
sure doesn't look that way to me :(
More information about the Digitalmars-d-learn
mailing list