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)

Hacktoberfest is happening now!



It is a month-long celebration of open source. For a lot of devs, its their introduction to open source.


Check out the Hacktoberfest tag on DEV to keep up with the latest!