Passing string from D to c++

monarch_dodra monarchdodra at gmail.com
Wed Jul 31 00:53:59 PDT 2013


On Tuesday, 30 July 2013 at 20:53:55 UTC, Dicebot wrote:
> On Tuesday, 30 July 2013 at 20:22:46 UTC, Milvakili wrote:
>> Thanks.  Is there any work in progress related to string 
>> passing?
>> I think string passing should be solved automatically.
>>
>> Coz otherwise one need to write wrapper for each c++ function 
>> that has a string parameter.
>>
>> thanks.
>
> c_function(toStringz("hello").ptr) does not seem that bad, what 
> is the issue here?

I want to point out that one of the dangers (as I've heard it, I 
haven't actually run into this), is that since the garbage 
collector won't scan your C function's internals, the caller 
*must* keep a reference in his code to preserve the allocated 
array. The above scheme does not do that: If the garbage 
collector runs after the start of the call, but before the end of 
the function, then you are in trouble.

I'd do it like this:
//----
string lifeline = toStringz("hello"); //Preserve reference
c_function(lifeline.ptr); //Make call
lifeline = null; //Release reference
//----

That's assuming c_function won't preserve the string somewhere. 
If it does, things get more complicated.


More information about the Digitalmars-d mailing list