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

Emmanuel Danso Nyarko emmankoko519 at gmail.com
Sat Nov 4 12:01:11 UTC 2023


On Saturday, 4 November 2023 at 11:18:02 UTC, Dadoum wrote:
> On Saturday, 4 November 2023 at 10:08:20 UTC, Imperatorn wrote:
>> On Saturday, 4 November 2023 at 03:00:49 UTC, Dadoum wrote:
>>> I was wondering why C++ linkage forbids strings as arguments 
>>> while we can with the C one.
>>>
>>> With C linkage, it's translated to a template that's defined 
>>> in the automatically generated header, but it just doesn't 
>>> compile in C++.
>>
>> Can you provide an example of exactly what you want to do?
>
> ```d
> extern (C) void hello(string arg) {
>     import std.stdio;
>     writeln(arg);
> }
> ```
>
> Compiles fine with dmd, ldc2 and gdc.
>
>
> ```d
> extern (C++) void hello(string arg) {
>     import std.stdio;
>     writeln(arg);
> }
> ```
>
> Doesn't compile.
>
> DMD: `Internal Compiler Error: type `string` cannot be mapped 
> to C++`
> GDC and LDC2: `function 'example.hello' cannot have parameter 
> of type 'string' because its linkage is 'extern(C++)'`
>
> And I am wondering why the type can be mapped to a template in 
> C but not in C++. (you can see the template used when you 
> compile with `-H --HCf=./header.h`

So C-strings are just an array of characters that are governed by 
simple functions and D strings also defined the same. So you 
could see that D strings are possibly built on the architecture 
of C strings. In C++, string is a complex standard template 
library that generates complex symbols and cannot be mapped as it 
is based on a standard library implementation.



More information about the Digitalmars-d-learn mailing list