String for C # from C ++ COM

I have a C ++ DLL and some functions return null terminated Unicode strings:

void SomeFunc(wchar_t* StrBuf)


The caller must allocate StrBuf - the string can be up to 256 characters long. This DLL also provides a COM object to use this DLL from C # via COM. Definition in IDL:

[id(1), helpstring("bla")]
HRESULT SomeFunc([in,out] BSTR* TextStr, [out,retval] LONG* RetValue);


Currently the C # code looks like this:

string val = new string('\0', 256); // Allocate memory
MyComObj.SomeFunc(ref val); // Get string
val = val.Substring(0, val.IndexOf('\0')); // Convert from null-terminated string


Is there a way to define such a COM function to make it easier to use from C #? It looks ugly now and takes three lines to call the function, or five lines if the function has two string parameters.


source to share

3 answers

solvable. In C ++, I use this code in a COM wrapper:

STDMETHODIMP MyClassClass::SomeFunc(BSTR* OptionValue, LONG* RetValue)
    *RetValue = 0;

    //... Copy text to txt variable
    *OptionValue = W2BSTR(txt);
    return S_OK;



[id(1), helpstring("")] HRESULT SomeFunc([out] BSTR* OptionValue, [out,retval] LONG* RetValue);


In C # it is now easy to call:

string val;
MyComObj.SomeFunc(out val);




If you have this exposed as a COM object, just use visual studio to add a reference to your object. It will automatically generate the assembly for you (I believe they call this COM wrapper).

This will call the methods of the .NET COM objects and will work unless you start trying to pass in some custom structures.

Here are some resources for you:

COM Callable Wrapper

COM Interop Part 1: Tutorial for C #



If memory for a string in the client allocates and fills it on the COM server, you should use a StringBuilder:

// IDL code
HRESULT GetStr(/*[out]*/ LPSTR pStr);

// Interop
void GetStr(/*[out]*/ [MarshalAs(UnmanagedType.LPStr)] StringBuilder pStr);

// C# code
var str = new StringBuilder(256);


Then the StringBuilder will be empty or filled with characters.



All Articles