How to call a COM function that returns a string when called from C #, Java


Problem Statement:

  1. Add a function to an existing COM library that returns a string.
  2. C# application consumes the COM library using the COM interop version (.net runtime assembly generated using tblimp)

Till now, I've tried the following variations:

Code on C++ side:

Variation 1: HRESULT GetString([out] BSTR* string);

Variation 2: HRESULT GetString([out,retval] BSTR* string);

Code on C# side:

string str;

Variation 1: GetString(out str);

Variation 2: str = GetString();

However both raise Attempt to read/write memory or similar worded exception.

Am I on the right track? Or are there some marshalling limitations that cause the exception to be raised (like when doing memory management etc) ? I could not find a clear explanation on the net as to which approach will work best for the above scenario, so this call for help.

Going further the plan is also that this COM function will be called from a Java app.

Note: Please disregard function syntax, might contain errors. The implemented code in COM works without any issues when called from within C++ COM library for both variations but fails for C# as stated above.

I suspect there is a problem in your C++ code. Assuming you're using ATL, one approach to returning a string is to do this:

HRESULT GetString([out,retval] BSTR* string)
    const char* ReturnString = "A string to return";
    *string = CComBSTR( ReturnString ).Detach();
    return S_OK;

Where ReturnString can be replaced with whatever string you wish to return.