0

Revised question:

We're using D7 to call a C# method that's in a COM object. The C# method returns a WideString.

Is there a risk that .NET will garbage collect the returned WideString from under our feet while we're using it in our Pascal code? If so, what alternatives do we have to safely return a string from a C# COM object?

Also, is our final Delphi line SubMan := nil the proper way to release the COM object?

C# Code

    [DispId(5)] 
    bool Test(int var1, ref int var2, ref string var3); 


    public bool Test(int var1, ref int var2, ref string var3) 
    { 
        bool result; 
        if (var1 == 0) 
        { 
            var2 = 0; 
            var3 = "zero"; 
            result = true; 
        } 
        else 
        { 
            var2 = -1; 
            var3 = "minus one"; 
            result = false; 
        } 
        return result; 
    } 

Pascal code from generated TLB in D7

function Test(     var1: Integer; 
               var var2: Integer; 
               var var3: WideString): WordBool; dispid 5;

Pascal code calling the COM object. Is there a risk var3 will be GC-ed?

procedure TForm1.Button1Click(Sender: TObject);
var
  SubMan: TSubMan;
  Var1: Integer;
  Var2: Integer;
  Var3: WideString;
  FunctionResult: Boolean;
begin
  SubMan :=  COTSubMan.Create;
  Var1 := 1;
  FunctionResult :=  SubMan.Test(Var1, Var2, Var3);  
  // Will Var3 above be persistent in the code 
  // or might it be garbage collected by .NET before we can use it below or later?
  ShowMessage( BoolToStr(FunctionResult, TRUE) + 
               ' Var2 = ' + IntToStr(Var2) + 
               ' Var3 = ' + Var3);
  SubMan := nil;  // Is this the right way to release the COM object?
end;
9
  • Please post the code in the C# Test method and the code in the Dephi client that calls Test. Does the EOleSysError happen calling into the method or returning from the method? Feb 18, 2014 at 4:44
  • If it's COM then use the COM string. Question lacks details. Feb 18, 2014 at 6:52
  • The code you have added is incomplete. Show the complete C# class declaration. Feb 18, 2014 at 8:12
  • Var3 (WideString) is reference counted. It will be deallocated when it leaves scope, i.e. when your method Button1Click() ends.
    – LU RD
    Feb 18, 2014 at 18:06
  • @LURD Just to confirm, even though the string was originally allocated in the C# COM object, var3 is safe to use throughout our Delphi Button1Click method? That's great news. May I ask how that happens? Is the var3 string a copy of the C# string that is created by Delphi as the COM call comes back from C#?
    – Tom
    Feb 18, 2014 at 18:29

2 Answers 2

3

The code in your question is fine. The COM marshaller handles the lifetimes of the two ref parameters for you. There's no danger from the GC because the semantics of the parameters is clearly expressed. The objects that you work with on the Delphi side are not .net objects and so not subject to GC.

Indeed, the GC is not a factor because this is COM. The fact that there is a .net object on the other side implemented the COM server is neither here nor there. It's the responsibility of the .net COM interop layer to present a valid COM object to you.

Just to confirm, even though the string was originally allocated in the C# COM object, var3 is safe to use throughout our Delphi Button1Click method?

Yes. Remember that this is COM, a standard for binary interop. You don't need to be too concerned by the details. FWIW, a WideString is the Delphi wrapper around the COM BSTR type. That string type is a UTF-16 encoded string, reference counted, and allocated off the shared COM heap. That last point is important. The fact that BSTR instances come of the shared COM heap is what allows them to be allocated in one module, and deallocated in another.

Is SubMan := nil the proper way to release the COM object?

Yes it is. Although it is a little pointless in this code because the local variable is about to leave scope and that will have the exact same effect as your nil assignment.

4
  • THANK YOU, @DavidHefferman! I really appreciate your taking the time to answer. As usual, the breadth and depth of your technical knowledge astonishes me! Thanks again for all of your help, not only on this question, but so many!
    – Tom
    Feb 18, 2014 at 21:37
  • That's very kind of you. Thanks. I'm amazed nobody else had chipped in. I'd have answer sooner had you prodded me! Thanks to @LURD for doing so. Feb 18, 2014 at 21:44
  • @DavidHefferman: Hey, I'd been waiting and hoping you'd pop in, David. And, if I knew how to prod you, I would have!
    – Tom
    Feb 19, 2014 at 18:23
  • You just did prod me with @NameOfProdee Feb 19, 2014 at 18:30
0

Using BSTR type is the easiest way since COM will handle memory (de)allocation.

eg:

Delphi:

function ReturnString(out TheString: WideString): Boolean; stdcall;
begin
  try
    TheString := 'Hello World';
  finally
    Result := True;
  end;
end;

C#:

[DllImport("mydll.dll", CallingConvention=CallingConvention.StdCall)]
public static extern bool ReturnString([MarshalAs(UnmanagedType.BStr)]out string TheString); 
1
  • I think you may have reversed the caller-callee scenario I am using. I've revised the question, hopefully making it clearer.
    – Tom
    Feb 18, 2014 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.