DEV Community

J N
J N

Posted on

D and C++: Passing strings

ex.cpp

#include <string>

const char* get_string() {
    return "Hello from C++!";
}

ex.d

extern (C++) {
  immutable(char)* get_string();
}

void main() {
  import std.conv : to;
  import std.stdio : writeln;

  string s = to!string(get_string());
  writeln(s);
}

And to compile:

  1. g++ -c -o cpp.o ex.cpp
  2. dmd ex.d cpp.o -L-lstdc++
  3. ./ex

It should print:

Hello from C++!

Top comments (0)