Re: COM allocator

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Heinz Ozwirk (wansor42_at_gmx.de)
Date: 07/25/04


Date: Sun, 25 Jul 2004 09:06:00 +0200


"benben" <benhongh@yahoo.com.au> schrieb im Newsbeitrag news:uJ2fQnXcEHA.3904@TK2MSFTNGP12.phx.gbl...
> Would the following code be valid? Presume that the client is NOT in the
> same appartment (single threaded) as the server.
>
> HRESULT MyJokeMachine::CreateJoke(/*out*/ LPSTR* joke)
> {
> *joke = new TCHAR[5000];
> //write a joke

You already did.
1. LPSTR is a pointer to char, TCHAR might by char or wchar_t.
2. Use BSTR to return strings. Not all clients can handle char strings.
3. Don't use new to allocate memory returned by COM methods. For strings use SysAllocString (or one of its friends). For other raw memory use the COM task allocator obtained from CoGetMalloc.

> return S_OK;
> }
>
> //and on client side
> IJokeMachine jokeBox;
IJokeMachine* jokeBox;
... and somehow create an object implementing IJokeBox.

> LPSTR joke;
BSTR joke;

> jokeBox->CreateJoke(&joke);
> MessageBox(NULL, joke, "", NULL);
> delete joke;
This is wrong, even by C++ standards. Memory allocated with nes[] must be freed with delete[]. But fpr strings returned from COM objects SysFreeString should be used. At least for those COM objects playing by the rules and using SysAllocString.

> jokeBox->Release();
>
> What if using the standard IMalloc interface?
>
> HRESULT MyJokeMachineUpdated::CreateJoke(/*out*/ LPSTR* joke, /*in*/
> IMalloc* allocator)

Usually there is no need to pass an allocator's interface. There may be clients that have no access to an allocator (scripts, for instance) and even for those that do, it's an extra burden. Make it simple and let the method call CoGetMalloc itself. And for strings, you can always use SysAllocString&Co.

HTH
    Heinz



Relevant Pages

  • Re: Using code pages
    ... getting corrupted between your client and mine... ... strings should work ... Just to avoid the char[] stuff. ...
    (microsoft.public.dotnet.languages.csharp)
  • Transfer files using sockets, urgent!!
    ... to client. ... int main(int argc, char *argv) ...
    (comp.unix.programmer)
  • Re: String concatenation function, request for comments.
    ... >> left to the client. ... If the resultant buffer is needed beyond the second ... >> If the strings specified for concatenation exceed the buffer available, ... > This demonstrates a fragility of the interface. ...
    (comp.lang.c)
  • Re: CORRECTION omniOrb server + java client
    ... virtual char* echoString; ... // Bind the context to root. ... I start this server and if I try to test with c++ client, ...
    (comp.object.corba)
  • Re: why does this work?
    ... char* channel; ... If you delete the assignment above, then client never gets ... init_irc_clientinitializes client in the main function ... Really bad luck, destined to fail only when you demonstrate your ...
    (comp.lang.c)