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

Imperatorn johan_forsberg_86 at hotmail.com
Sat Nov 4 12:07:12 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`

We can just assume what you're doing on the C++-side. Are you 
using std::string?

You could try as a pointer + length and it might work, but 
without seeing your complete code it's quite hard to know what 
you want to do.


More information about the Digitalmars-d-learn mailing list