Right click on an IListManager icon in
the ClassView tree (or IPasswordManager if you have chosen to use the exising
ChgPass component), and select "Add Method". Enter GetArray under
method name, and
[out, retval]VARIANT * pVal
under Parameters.
Our method will use the vector template
object found in the Standard Template Library (STL) to store a list of
string values that we will use to populate our Safe Array. We are doing
it purely for the sake of demonstration: vector is an extremely
useful class that we will use all over the place in the future articles.
To use the vector template, open StdAfx.h and add the following #include:
StdAfx.h
extern CComModule _Module;
#include <atlcom.h>
#include
<vector> |
If we now try to compile the project, we will
get the compile warning
warning C4530: C++ exception handler used,
but unwind semantics are not enabled. Specify -GX
c:\program files\microsoft visual studio\vc98\include\xstring(521) : while
compiling class-template member function 'void __thiscall std::basic_string<char,struct
std::char_traits<char>,class std::allocator<char> >::_Copy(unsigned
int)'
To get rig of that warning, go to Project/Settings,
open C/C++ tab, select "C++ Language" and check off "Enable Exception Handling".
Then click OK and build the project again.
We can now go ahead and add code for the GetArray
method:
ListManager.cpp
STDMETHODIMP CPasswordManager::GetArray(VARIANT
*pVal)
{
//
Create an array of names and fill it with dummy values
std::vector<CComBSTR>
arrNames;
arrNames.push_back(
"John Smith" );
arrNames.push_back(
"Ian Granovksi" );
arrNames.push_back(
"Tao Chan" );
//
Build and return a Safe Array of Variants
VariantInit(
pVal );
pVal->vt
= VT_ARRAY | VT_VARIANT;
int
nSize = arrNames.size();
SAFEARRAY
* psa;
SAFEARRAYBOUND
bounds = { nSize, 0 };
psa
= ::SafeArrayCreate( VT_VARIANT, 1, &bounds );
VARIANT
* VarArray;
::SafeArrayAccessData(
psa, (void **) &VarArray );
int
i = 0;
std::vector<CComBSTR>::iterator
it;
for(
it = arrNames.begin(); it != arrNames.end(); it++, i++ )
{
VarArray[i].vt = VT_BSTR;
VarArray[i].bstrVal = ::SysAllocString( (* it ).m_str );
}
SafeArrayUnaccessData(
psa );
pVal->parray
= psa;
return S_OK;
} |
After the project is built we can go ahead and
test the GetArray method with the following simple ASP script:
<HTML>
<BODY>
<%
Set ListObj = Server.CreateObject("SafeArray.ListManager")
' or Set ListObj = Server.CreateObject("ChgPass.PasswordManager")
MyList = ListObj.GetArray
For i = 0 to UBound(
MyList )
Response.Write
MyList(i) & "<BR>"
Next
%>
</BODY>
</HTML> |