
Howto Expose a normal C++ class with methods via an Interface Class in ATL COM
Bill, in your IDL, you will want something like:
HRESULT FromString([in] BSTR bsInput);
HRESULT ToString([out,retval] BSTR* bsOutput);
In your class you will either want to store your strings as CComBSTR's, in
which case your methods would look like:
STDMETHODIMP CObj::FromString(BSTR bsInput)
{
this->m_cbsVar = bsInput;
return S_OK;
Quote:
}
STDMETHODIMP CObj::ToString(DisplayType iDisplayType, BSTR *bsOutput)
{
this->m_cbsVar.CopyTo(bsOutput);
return S_OK;
Quote:
}
Or, alternatively, you can use stl::wstrings. This would look like:
STDMETHODIMP CObj::FromString(BSTR bsInput)
{
this->m_wsVar = bsInput; // Convert to a std::wstring
return S_OK;
Quote:
}
STDMETHODIMP CObj::ToString(DisplayType iDisplayType, BSTR *bsOutput)
{
CComBSTR cbsOutput(this->m_wsVar.c_str()); // Convert from a
std::wstring to a CComBSTR
*bsOutput = cbsOutput.Detach(); // Convert
from a CComBSTR to a BSTR
return S_OK;
Quote:
}
The advantage of the std::wstring is that you get a whole lot more
functionality than the CComBSTR. Unfortunately you are stuck with using the
BSTR when making calls through the COM layer, but inside your class you can
do what you please. If you just need to hold onto a string, simply use the
CComBSTR.
Have a read through the following for a good description of how to use
BSTR's in COM:
http://www.geocities.com/Jeff_Louie/bstr.html
Don't be tempted, as I was at first, to use std::strings internally, and
convert to them with the A2W macro. BSTR's are wide, so converting to
std::string is a lossy conversion. This comes back to bite you when you
realize that you need to support multi-byte languages.
- Julien
Quote:
> How do I expose the method of a class in COM. The method
> must accept a String variable, Edit the accepted string
> variable and return a string variable.
> I created a ATL COM Project called MyFirstCOMMDLL.
> Inserted a Class called MyFirstClass which then also gives
> me an interface to the class called IMyFirstClass.
> Then add a method to the Interface called MyFirstMethod
> (BSTR strInput).
> My problem is working with the BSTR or VARIANT. More
> specifically assigning values to BSTR's/VARIANT's.
> Basically I am looking for the equivalent of CString
> (creation, parsing, editing, etc etc).