Why can a WideString not be used as a function return value for interop?

后端 未结 2 527
南方客
南方客 2020-11-22 12:23

I have, on more than one occasion, advised people to use a return value of type WideString for interop purposes.

  • Accessing Delphi DLL throwing oc
2条回答
  •  甜味超标
    2020-11-22 12:41

    In C#/C++ you will need to define the Result as out Parameter, in order to maintain binary code compatibility of stdcall calling conventions:

    Returning Strings and Interface References From DLL Functions

    In the stdcall calling convention, the function’s result is passed via the CPU’s EAX register. However, Visual C++ and Delphi generate different binary code for these routines.

    Delphi code stays the same:

    function TestWideString: WideString; stdcall;
    begin
      Result := 'TestWideString';
    end;
    

    C# code:

    // declaration
    [DllImport(@"Test.dll")]        
    static extern void  TestWideString([MarshalAs(UnmanagedType.BStr)] out string Result);
    ...
    string s;
    TestWideString(out s); 
    MessageBox.Show(s);
    

提交回复
热议问题