November 12th, 2005, 10:52 PM
#1
Windows SDK String: What are the rules for BSTR allocation and deallocation?
Q: What are the rules for BSTR allocation and deallocation ?
A:
Case 1: BSTR passed by value
ODL/IDL method signature:
Code:
[id(1), helpstring("method SomeMethodRule1" )] HRESULT SomeMethodRule1([in] BSTR bstrParam);
Client side rules:
Client allocates and deallocates BSTRs
Client side example code:
Code:
{
BSTR bstrParam = SysAllocString(L"Test" );
if (SUCCEEDED(pTestBstr->SomeMethodRule1(bstrParam)))
{
//use bstrParam
}
//done.. Now free..
SysFreeString(bstrParam);
}
Server side rules:
None
Server side example code:
Code:
STDMETHODIMP CBSTRTest::SomeMethodRule1(BSTR bstrParam)
{
// TODO: Add your implementation code here
MessageBox(NULL,bstrParam,_T("MethodRule1" ),MB_OK);
return S_OK;
}
Case 2: BSTR passed by reference
ODL/IDL method signature:
Code:
[id(2), helpstring("method SomeMethodRule2" )] HRESULT SomeMethodRule2([in,out] BSTR* bstrParam);
Client side rules:
Client allocates and deallocates BSTRs
Client side example code:
Code:
{
BSTR bstrParam = SysAllocString(L"Test" );
if (SUCCEEDED(pTestBstr->SomeMethodRule2(&bstrParam)))
{
//use bstrParam
MessageBox(NULL,bstrParam,_T("New value" ),MB_OK);
}
//done.. Now free..
SysFreeString(bstrParam);
}
Server side rules:
Server can replace the BSTR with a new one, hence returning the new one to the client
Server side example code:
Code:
STDMETHODIMP CBSTRTest::SomeMethodRule2(BSTR *bstrParam)
{
// TODO: Add your implementation code here
MessageBox(NULL,*bstrParam,_T("MethodRule2" ),MB_OK);
//now reallocate if required
SysReAllocString(bstrParam,L"newValueRule2" );
//or modify existing one if required
return S_OK;
}
Case 3: BSTR returned from server
ODL/IDL method signature:
Code:
[id(3), helpstring("method SomeMethodRule3" )] HRESULT SomeMethodRule3([out] BSTR* bstrParam);
Client side rules:
Client does not allocate. Client deallocates.
Client side example code:
Code:
{
BSTR bstrParam;
if (SUCCEEDED(pTestBstr->SomeMethodRule3(&bstrParam)))
{
//use bstrParam
MessageBox(NULL,bstrParam,_T("New value" ),MB_OK);
//Done.. Now free..
SysFreeString(bstrParam);
}
}
Server side rules:
Server allocates BSTR.
Server side example code:
Code:
STDMETHODIMP CBSTRTest::SomeMethodRule3(BSTR *bstrParam)
{
// TODO: Add your implementation code here
*bstrParam = SysAllocString(L"newValueRule3" );
return S_OK;
}
Attached Files
Last edited by Andreas Masur; November 13th, 2005 at 08:25 AM .
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width