On 2013-07-10 19:18, JohnnyK wrote:
I hope you like the subject matter and I hope it is not too simplistic
or have been answered before.
   Anyway I have a question about how the garbage collector works in a
very specific situation.  When passing string type to a function in a
shared library or DLL and assigning it to a variable of type string
inside the function and returning the internal string.  Such as this.

export string mytest(string tstStr)
{
   string st = tstStr;
   /* abbreviated to protect the innocent but other operations
      such as concatenating and deleting may be done to st before the
return
   */
   return st;
}

Is the string type a pointer or is it something else?  In the line where
tstStr is assigned to st does it copy the address in tstStr to st or
does it copy the value in tstStr?  I am just a bit confused about string
types since I come from a C background and C has no type like this.
Also what is returned by this function?  Does this function return a
pointer or the contents of an array?  If I do export this what does it
do to the Garbage Collection?  Does the Garbage Collection collect
tstStr or st? Also notice the comment in the function.

A string in D, and all arrays, is a struct looking like this:

struct Array (T)
{
    T* ptr;
    size_t length;
}

"string" happens to be an alias looking like this:

alias immutable(char)[] string;

That means you can do all operations on a string except assigning to specific elements:

string str = "foo";
str ~= "bar"; // ok
auto str2 = str ~ "foo"; // ok
str[0] == "f"; // ok
str[0] = 'a'; // error, cannot assign to immutable
auto str3 = str[1 .. 3]; // ok

It won't collect anything along as it is scope. If a variable goes out of scope and nothing else points to that data it will collect it (eventually).

Hope this helps a bit.

--
/Jacob Carlborg

Reply via email to