Re: COM allocator
From: Heinz Ozwirk (wansor42_at_gmx.de)
Date: 07/25/04
- Next message: Heinz Ozwirk: "Re: SetWindowPos"
- Previous message: Jerry Coffin: "Re: Listing all files under a directory"
- In reply to: benben: "COM allocator"
- Messages sorted by: [ date ] [ thread ]
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
- Next message: Heinz Ozwirk: "Re: SetWindowPos"
- Previous message: Jerry Coffin: "Re: Listing all files under a directory"
- In reply to: benben: "COM allocator"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|