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

Paul Backus snarwin at gmail.com
Sat Nov 4 14:21:49 UTC 2023


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++.

`extern(C++)` functions use C++ name mangling, which includes the 
types of the parameters in the mangled name. However, since C++ 
does not have a built-in slice type like D's `T[]`, there is no 
valid C++ mangling for a D slice. Because of this, it is 
impossible to compile an `extern(C++)` function that has a D 
slice as a parameter.

As a workaround, you can convert the slice to a `struct`:

```d
struct DSlice(T)
{
     T* ptr;
     size_t length;

     T[] opIndex() => ptr[0 .. length];
}

DSlice!T toDslice(T)(T[] slice)
{
	return DSlice!T(slice.ptr, slice.length);
}

extern(C++) void hello(DSlice!(const(char)) arg)
{
     import std.stdio;
     writeln(arg[]);
}

void main()
{
	const(char)[] greeting = "hello";
	hello(greeting.toDslice);
}
```


More information about the Digitalmars-d-learn mailing list