Click to See Complete Forum and Search --> : COM String passing


Roman B
September 13th, 1999, 07:05 AM
I want to pass a String over a COM object. I tried to decalre the fuction in IDL as follows:
[id(4), helpstring("method GetQuestionText")] HRESULT GetQuestionText([in, out, string] wchar_t **frtxt, [out, retval] int *result);
The first problem is, that the idl-compiler trows a warning that this is not compatible with [oleautomation]. Whats wrong. Is the OLE not possible to pass such pointer over the interface. The Second problem is, that I allocate memory with CoTastMemAlloc in the COM object and want to free it with CoTaskMemFree in the client. However the system abort my program in the kernel, with an error.
Can anybody help me please.

Wayne Fuller
September 13th, 1999, 07:17 AM
I can answer the first question.

In order to be compatible with Ole Automation, you
have to use BSTR's for strings. The reason is because
VB looks at strings different than C or C++. A BSTR is
just like a regular string, but the first two bytes tell
how long the string is. You can use wide characters but
VB will not be able to use the function.

jeffbarth
September 14th, 1999, 12:08 PM
RE: First question. The previous post is correct about using BSTRs. But the warning is just a warning. If you are passing data between COM objects that you know are writtin in C++, you can pass almost anything.

RE: The second question. For all top-level pointers, the caller must manage the memory. Thus, you need to allocate memory for the returned string in your client, and pass a pointer to that memory. The server puts the string in your allocated memory buffer. IDL has other features for you to specify how big the buffer is, and for the server to tell you how many characters were actually copied (refer to the "size_is" attribute.

CoTaskMemAlloc/Free is only used for memory pointed-to by embedded pointers, i.e. a pointer within a structure. For example, a server could return a linked list of data. The client passes in a 'head' pointer, the server allocates all nodes of the list with CoTaskMemAlloc, builds the list and returns it. The client needs to de-alloc each node of the list with CoTaskMemFree.

See the "Wicked Code" column by Jeff Prosise in the May 1999 MSJ.