returning D string from C++?

bitwise via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 13:17:23 PDT 2017


I have a Windows native window class in C++, and I need a 
function to return the window title.

So in D, I have this:

// isn't D's ABI stable enough to just return this from C++
// and call it a string in the extern(C++) interface? anyways..
struct DString
{
     size_t length;
     immutable(char)* ptr;
     string toString() { return ptr[0..length]; }
     alias toString this;
}

extern(C++) interface NativeWindow {
     DString getTitle() const;
}

and in C++, this:

class NativeWindow
{
public:
     struct DString {
         size_t length;
         const char* ptr;
     };

     virtual DString getTitle() const {
         DString ret;
         ret.length = GetWindowTextLength(_hwnd) + 1;
         ret.ptr = (const char*)gc_malloc(ret.length, 0xA, NULL);
         GetWindowText(_hwnd, (char*)ret.ptr, ret.length);
         return ret;
     }
};

So while it's not generally safe to _store_ pointers to D's GC 
allocated memory exclusively in C++, I've read that D's GC scans 
the stack, and getTitle() is being called from D(and so, is on 
that stack..right?). So is the string I'm returning safe from GC 
collection?

   Thanks



More information about the Digitalmars-d-learn mailing list