How to pass strings between D and C ++?

I tried to adapt this answer ...

stack overflow

... so I passed the C ++ string to D, and then returned it with the answer "-response", but could not compile the D file:

// dtest.d
extern (C++) string dfunc(string s) {
        return s ~ "response";
}

$ dmd -c dtest.d
Error: Internal Compiler Error: unsupported type string

dmd: cppmangle.c:576: virtual void CppMangleVisitor::visit(Type*): Assertion `0' failed.
Aborted (core dumped)

Then I do not know how to compile a C ++ file so that it passes this value correctly and receives it correctly.

+4
source share
3 answers

You can go from line D with zero completion with std.string.toStringz. In the same way there is std.string.fromStringz:

extern (C++) immutable(char)* dfunc(const char* s) {
    import std.string;
    return toStringz(fromStringz(s) ~ "response");
}

And then the caller in C ++

#import <Cocoa/Cocoa.h>
char *dfunc(const char *);
extern "C" int rt_init();
extern "C" int rt_term();

int main(int argc, const char * argv[]) {

        const char *sTest = "request";
        rt_init();
        NSLog(@"Result=%s",dfunc(sTest));
        rt_term();

  return NSApplicationMain(argc, argv);
}
+3
source

Line D is a structure with length char*and length size_t. This is incompatible with std :: string

API C, char * .

, , D- ++-, ++- D- .

+2

This question has been asked many times on SO. I think one of the best answers is given here: fooobar.com/questions/472900 / ...

Note: hands down, the answer is related to C, but it can also be applied to C ++.

0
source

Source: https://habr.com/ru/post/1619466/


All Articles