Why can't we use strings in C++ methods?

Basile B. b2.temp at gmx.com
Sat Nov 4 14:33:56 UTC 2023


On Saturday, 4 November 2023 at 13:51:20 UTC, Dadoum wrote:
> On Saturday, 4 November 2023 at 13:45:56 UTC, Emmanuel Danso 
> Nyarko wrote:
>> [...]
>>
>> There is a syntax disagreement here that's why the D compiler 
>> is instantly stopping you from doing any symbol generated 
>> interaction with string in C++ interop. C++ doesn't know 
>> 'string' and C++ mangles with parameters and so passing string 
>> will make string get involved with the symbol generation and 
>> since string(std::string) in C++ is a template library, the D 
>> compiler stops you from engaging with 'string'
>
> I don't think it's related to the existence of std::string at 
> all since all dynamic array types are forbidden.
>
> ```d
> extern (C++) void hello(ubyte[] arg) {
>         import std.stdio;
>         writeln(arg);
> }
> ```
>
> also fails to compile while this works:
>
> ```d
> extern (C) void hello(ubyte[] arg) {
>         import std.stdio;
>         writeln(arg);
> }
> ```


The type simply cannot be mangled using the C++ mangler as it 
does not exist over there. You might have the impression that 
this should be allowed, e.g as an extension, but keep in mind 
that `extern(C++)` is firstly designed to link against object 
produced by a C++ compiler.

Now why this works in `extern(C)` ? Because C does not mangle the 
parameters, a function linkage name is simply its unqualified 
name, so linking will work even if the parameter types are 
specific  to D.

Now there is still the question whether the `extern(C)` code will 
work as expected or not.


More information about the Digitalmars-d-learn mailing list