C++, COM and passing strings - c++

I am debugging some other programmer's source code of a Windows Media Player plugin. This plugin causes WMP to crash sometimes, and sometimes it takes really long time to open plugin settings window. The problem occurs only when opening settings window while music is being played back. It opens without issues if the player is stopped.
While looking through the code and debugging, I have came to the line of code which seems to be the cause of the problems.
The property page has the following member variable:
CComPtr<IDsp_plugin> m_pDsp_plugin;
and the property page at initialization calls get_text method of the COM object:
unsigned char * txt = NULL;
//m_pDsp_plugin is a valid pointer to IDsp_plugin
HRESULT res = m_pDsp_plugin->get_text(&txt);
At this moment hres is "0x80010105: The server threw an exception." and Visual Studio Debug output shows "First-chance exception at 0x764efbae in wmplayer.exe: 0x80010105:
get_text method is defined as follows:
in Dsp_plugin.idl
interface IDsp_plugin : IUnknown
{
HRESULT get_text([out] unsigned char* *pVal);
...
in Dsp_plugin.h
class ATL_NO_VTABLE CDsp_plugin :
public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<CDsp_plugin, &CLSID_Dsp_plugin>,
public IDsp_plugin,
public IMediaObject,
public IWMPPluginEnable,
public ISpecifyPropertyPages
{
STDMETHOD(get_text)(unsigned char* *txt);
...
and finally the method itself which throws this exception:
Dsp_plugin.cpp
STDMETHODIMP CDsp_plugin::get_text (unsigned char* *txt)
{
... // some code for copying a valid string from somewhere to char* y
// 11 bytes of memory for y was allocated using malloc(10+1);
// y contains a valid C string here, tested with debugger and passing to OutputDebugStringA
*txt = (unsigned char*)(y); // This line executes normally, but at the end the caller gets "The server threw an exception." and WMP starts behaving weirdly.
// If I comment it out, the caller gets S_OK and there are no any issues with WMP.
return S_OK;
}
The COM DLL is compiled with setting "Use Unicode Character Set".
I am not experienced COM programmer, but passing strings as unsigned char** seems unusual to me, I have seen mostly BSTR or VARIANT when dealing with COM.
Maybe some COM guru can explain, why this exception happens and can it be possibly fixed just by converting methods to using BSTR* and SysAllocString/SysfreeString instead of unsigned char**/malloc/free ?

Put simply, COM doesn't know how to pass around pointers of type unsigned char *. The default marshalling rules are applied (since the interface definition doesn't specify any parameter attributes), and, if I'm interpreting this correctly, COM marshals the outer pointer itself txt properly, but treats *txt as a pointer to a single unsigned char, not a string.
This may still work if the caller and callee happen to be in the same apartment; from the sounds of it, they're not.
The easiest solution is simply to make the parameter a BSTR *. COM has special handling for BSTR which will ensure it's passed correctly.

Related

Why I can call StringFromCLSID even without the calling of CoInitializeEx before?

I am learning COM through C++. From MSDN:
Applications are required to use CoInitializeEx before they make any
other COM library calls except for memory allocation functions.
The memory allocation functions is CoTaskMemAlloc and CoTaskMemFree in my opinion.
But I see, my "Hello World" works fine with and without the CoInitializeEx and CoUninitialize functions calling. In my code I use the StringFromCLSID function which is declared in the combaseapi.h header. So, it is a COM function in my opinion. My code:
/* entry_point.cpp */
#include "Tools.h"
#include <objbase.h>
int main(){
HRESULT hr = ::CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (FAILED(hr)){
trace("Can't initialize COM for using in the current thread.");
keep_window_opened();
return 1;
}
// {D434CF7D-2CDD-457A-A4EF-5822D629CE83}
static const CLSID clsid =
{ 0xd434cf7d, 0x2cdd, 0x457a, {
0xa4, 0xef, 0x58, 0x22, 0xd6, 0x29, 0xce, 0x83 } };
const size_t SIZE = 39;
wchar_t* wch = nullptr;
hr = ::StringFromCLSID(clsid, &wch);
if (FAILED(hr)){
trace("Can't convert CLSID to wchar_t array.");
}
else{
trace("CLSID converted to wchar_t array.");
char mch[SIZE];
size_t count = 0;
int result = ::wcstombs_s(&count, mch, wch, SIZE);
if (result){
trace("Can't convert wchar_t array to char array.");
}
else{
trace(mch);
}
::CoTaskMemFree(wch);
}
::CoUninitialize();
keep_window_opened();
return 0;
}
If I remove the calls of CoInitializeEx and CoUninitialize functions, then my code works still. I expected it will not work...
Why StringFromCLSID work even without the calling of CoInitializeEx before?
Thank you.
StringFromCLSID is basically a printout of GUID value (bytes) into string, then formatting it nicely with hyphens and braces. There is nothing else involved and hence COM initialization is not really needed for this call to succeed.
You have to do CoInitialize/CoInitializeEx to be safe, but not doing it you don't necessarily hit a problem right away.
Why StringFromCLSID work even without the calling of CoInitializeEx before?
The key information is stated right in the documentation.
CoInitializeEx function:
You need to initialize the COM library on a thread before you call any of the library functions except ... the memory allocation functions. Otherwise, the COM function will return CO_E_NOTINITIALIZED.
StringFromCLSID function:
StringFromCLSID calls the StringFromGUID2 function to convert a globally unique identifier (GUID) into a string of printable characters.
The caller is responsible for freeing the memory allocated for the string by calling the CoTaskMemFree function.
StringFromCLSID() returns a dynamically allocated string. We can infer from the highlighted sentence above that the memory is allocated using CoTaskMemAlloc() - which is explicitly documentated as not requiring CoInitializeEx().
StringFromGUID2() formats GUID data into a caller-specified memory block. Formatting a string does not require COM functionality. The wsprintfW(), StringCbPrintfW(), or other equivalent function would suffice. So CoInitializeEx() should not be required for StringFromGUID2(), even though this is not explicitly documented. I think it would be pretty short-sighted for Microsoft to not use one of their many available string formatting functions to implement StringFromGUID2(). So I think it should be safe to say that CoInitializeEx() is not a requirement for this (unless Microsoft says otherwise).
The GUID structure simply contains a few numbers and bytes. Declaring and using a GUID is not dependent on the COM library. You can freely use a GUID in your code all you want without touching COM at all - unless you want to generate a new GUID, in which case the CoInitializeEx() requirement for CoCreateGUID() is blurry as CoCreateGUID() is in the COM library but is explicitly documented as simply calling UuidCreate(), which is in the RPC library instead.
So that is why you can call StringFromCLSID() without calling CoInitializeEx() first. A GUID on its own does not require COM initialization. The string is being allocated with a memory function that does not require COM initialization. And the string is being formatted in a manner that most likely does not require COM initialization.

Cannot get a BSTR in VB6 dll from a referenced C++ dll

Let me start off by saying that VB is not my strong suit.
I am developing a C++ dll to be used in a VB6 application's dll.
I have successfully instantiated the (C++) classes in VB. I am trying to access data members of the class using this syntax: "vbCppObj.dataMemberName".
I can confirm that this works for boolean and enum types and it invokes the getter methods defined in my class.
I have to access a string from the (C++) class as well.
The getter function for the string is given below:
class MyCPPClass
{
private:
WCHAR* CPPErrorString = L"This is a string";
public:
HRESULT __stdcall get_CPPErrorString(BSTR* pVal)
{
BSTR str = ::SysAllocString(CPPErrorString);
if(str)
*pVal = str;
return S_OK;
}
};
I am unable to debug the C++ dll right now.
I access this value in the VB6 code as follows:
ErrorString = vbCppObj.CPPErrorString
Logger.log "[Log]:" & ErrorString
"ErrorString" is a String type in VB. When this line executes, the "ErrorString" object shows "<Out of memory>" (when I hover over it). If I step further, to the logging code, it gives me a "Error 14: Out of string space".
Also, I have typed this code in the browser so, it may not be 100% correct.
As it turns out, I had to convert the string into a "_b_str" and then to a "BSTR". That worked for me.
I had tried it earlier but I don't know why it didn't work at that time.
Why you just don't use LPCTSTR?
I'm not an advanced C/C++ programmer, but this should work
class MyCPPClass
{
private:
LPCTSTR CPPErrorString = "This is a string";
public:
HRESULT __stdcall get_CPPErrorString(LPCTSTR * pVal)
{
// copy the value
*pVal = CPPErrorString;
// return
return S_OK;
}
}

About _variant_t type in a MFC Library

inside my MFC (VC2010 SP1) project, I'm widely using a third party library to write some data in a database. This library is quite old (I've found it compiled for VS2005) and uses _variant_t to handle data.
In a particular case anyway I get a strange behaviour, I'll try to explain it:
// .h
struct myData
{
blastuff
CString strMyCode;
};
class MyClass
{
protected:
myData m_Foo;
};
// .cpp
// In OnInitDialog:
//...
TrdPartRecordset *pRS;
//...
pRS->GetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Now, I do my job and when user press OK, it's time to save to database and here start the problems:
// In OnOK
TrdPartRecordset *pRS;
//...
pRS->SetFieldValue( _T("MyDBColumn"), m_Foo.strMyCode );
Problem: if I do not modify m_Foo.strMyCode, I don't have any problem. What if I modify it? Well, if m_Foo.strMyCode does NOT contain ANY number, still have no problem.
Instead, when I have a number, I get a nasty error:
Unhandled exception at 0x77772d37 in Mosaico.exe: 0xC0000005: Access violation reading location 0x9d7077b7.
which is an attempt to read a deleted location. I've checked m_Foo in the watch and it's correct and valid, so I've digged into library source code:
BOOL TrdPartyRecordset::SetFieldValue(LPCTSTR lpFieldName, CString strValue)
{
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld.vt = VT_BSTR;
else
vtFld.vt = VT_NULL;
vtFld.bstrVal = strValue.AllocSysString();
BOOL bret = PutFieldValue(lpFieldName, vtFld);
SysFreeString(vtFld.bstrVal);
return bret;
}
What it happens is that vtFld is valid until SysFreeString and it get destroyed after it (I can see it proceding step-by-step with debugger), but ONLY WHEN I HAVE NUMBERS INTO strValue. This doesn't happen when strValue is pure alphabetical.
I've searched around the Internet and found that this kind of error happens when you double release a resource and so I've commented out SysFreeString and boom goes the dynamite: no more crashes.
Anyway is a better programmer than me so I guess that if he put that SysFreeString he had his reasons, moreover, this is the only part of my program where this mechanism crashes.
My question is: do I lose memory commenting out that SysFreeString?
Another one: do you have better solutions?
The reason is simple:
The memory is freed twice!
_variant_t has a destructor. Set the type to VT_BSTR. You also see the pojnter and type to VT_BSTR
After the function you call, you free the memory again and the destructor does the same.
The code should look like this:
_variant_t vtFld;
if(!strValue.IsEmpty())
vtFld = strValue;
else
vtFld.vt = VT_NULL;
return PutFieldValue(lpFieldName, vtFld);

ATL C++ memory leak with safearray of ccomobjects

I find myself in need of help. Now, I'm not all that unfamiliar with C++, but combining it with ATL provides a whole new level of confusion. Anyways, my problem: I (finally) managed to return an array of objects in my COM method to C# caller. But upon 'testing' (running said function a number of times repeatedly) I recognized a small memory leak.
IDL excerpt:
...
interface IDISControl : IDispatch{
...
[id(12)] HRESULT GetNets([out,retval] VARIANT* nets);
};
Header excerpt:
...
STDMETHOD(GetNets)(VARIANT* nets);
...
Code:
STDMETHODIMP CDISControl::GetNets(VARIANT* nets)
{
SNet *netz;
int32_t num;
int result, i;
result = DIS_GetNetNum(securityHandle, &num);
netz = new SNet[num];
result = DIS_GetNet(securityHandle, netz, num); //getting some data
CComSafeArray<IDispatch*> netArray;
CComObject<CDISNet> *net;
CComVariant *var;
netArray.Create(num, 0);
for (i = 0;i<num;i++){
CComObject<CDISNet>::CreateInstance(&net);
if (net == NULL)
return S_FALSE;
net->AddRef();
net->Convert(netz[i]);
netArray[i] = net;
net->Release();
net = NULL;
}
CComVariant val(netArray.Detach());
val.Detach(nets);
delete [] netz;
netArray.Destroy();
return S_OK;
}
I instantiate CDISNet objects and put some data in them (Convert()). I put them in my safearray and release. As I understand it, the responsibility for destroying them is transferred to safearray. Afterwards, I box the array in a VARIANT so I can fill my [out, retval] parameter. Since it's an out parameter, the responsibility for destruction should be transferred to caller (in my case C#, i.e. its GarbageCollector). I dispose of my dynamic array 'netz' and I destroy safearray wrapper.
So what am I missing? What is left allocated? (This project is really making me appreciate all the comforts of .net).
Help. Please.
EDIT: Further debugging revealed to me that the problem is certainely in my CComObject objects. They aren't being deallocated. If I delete net; in each iteration the array also looses data. I'm unsure as how to rectify that...
EDIT2:
Ok, I poked around this code for a bit, and the leak seems to go away when I comment out variant boxing. The problem is that I borrowed this piece of code from Visual Studio sample on safearrays. So, does anyone have any idea what's up with:
CComVariant val(netArray.Detach());
val.Detach(nets);
...and what to do about it?
Most, if not all, of ATL's wrappers follow COM conventions -- they copy/addref incoming data, as their destructor will destroy/release.
So when you pass your detached SAFEARRAY to CComVariant's constructor, it will make a copy of the SAFEARRAY, which means nobody releases the result from CComSafeArray::Detach.
In cases like this, I always found it easier to forego the wrapper for the return value entirely;
nets->vt = VT_ARRAY | VT_DISPATCH;
nets->parray = netArray.Detach();
The alternative would be to pass your CComSafeArray directly to CComVariant's constructor, without calling Detach, but that would cost you an extra copy. I'd prefer the raw access presented above, as it is most straightforward and cheapest.
As to your first edit, what you're doing with AddRef/Release is fine, if somewhat unnecessary. CComObject::CreateInstance returns an object with reference count 0, so the AddRef will bring it to 1, and then assigning it to the CComSafeArray will bump it to 2, and the following Release back down to 1.
Unless the Convert method does anything with the object's reference count (e.g. QueryInterface itself or pass itself to another COM method), you could skip the AddRef/Release pair, and let Convert execute with refcount == 0. Then adding it to the array would increase it, and it would stay alive until released.

Pointer object in C++

I have a very simple class that looks as follows:
class CHeader
{
public:
CHeader();
~CHeader();
void SetCommand( const unsigned char cmd );
void SetFlag( const unsigned char flag );
public:
unsigned char iHeader[32];
};
void CHeader::SetCommand( const unsigned char cmd )
{
iHeader[0] = cmd;
}
void CHeader::SetFlag( const unsigned char flag )
{
iHeader[1] = flag;
}
Then, I have a method which takes a pointer to CHeader as input and looks
as follows:
void updateHeader(CHeader *Hdr)
{
unsigned char cmd = 'A';
unsigned char flag = 'B';
Hdr->SetCommand(cmd);
Hdr->SetFlag(flag);
...
}
Basically, this method simply sets some array values to a certain value.
Afterwards, I create then a pointer to an object of class CHeader and pass it to
the updateHeader function:
CHeader* hdr = new CHeader();
updateHeader(hdr);
In doing this, the program crashes as soon as it executes the Hdr->SetCommand(cmd)
line. Anyone sees the problem, any input would be really appreciated
When you run into a crash, act like a crime investigator: investigate the crime scene.
what is the information you get from your environment (access violation? any debug messages? what does the memory at *Hdr look like? ...)
Is the passed-in Hdr pointer valid?
Then use logical deduction, e.g.:
the dereferencing of Hdr causes an access violation
=> passed in Hdr points to invalid memory
=> either memory wasn't valid to start with (wrong pointer passed in), or memory was invalidated (object was deleted before passing in the pointer, or someone painted over the memory)
...
It's probably SEGFAULTing. Check the pointers.
After
your adding some source code
your comment that the thing runs on another machine
the fact that you use the term 'flag' and 'cmd' and some very small datatypes
making me assume the target machine is quite limited in capacity, I suggest testing the result of the new CHeader for validity: if the system runs out of resources, the resulting pointer will not refer to valid memory.
There is nothing wrong with the code you've provided.
Are you sure the pointer you've created is the same same address once you enter the 'updateHeader' function? Just to be sure, after new() note the address, fill the memory, sizeof(CHeader), with something you know is unique like 0XDEAD, then trace into the updateHeader function, making sure everything is equal.
Other than that, I wonder if it is an alignment issues. I know you're using 8 bit values, but try changing your array to unsigned ints or longs and see if you get the same issue. What architecture are you running this on?
Your code looks fine. The only potential issue I can see is that you have declared a CHeader constructor and destructor in your class, but do not show the implementation of either. I guess you have just omitted to show these, else the linker should have complained (if I duplicate this project in VC++6 it comes up with an 'unresolved external' error for the constructor. It should also have shown the same error for the destructor if you had a... delete hdr; ...statement in your code).
But it is actually not necessary to have an implementation for every method declared in a class unless the methods are actually going to get called (any unimplemented methods are simply ignored by the compiler/linker if never called). Of course, in the case of an object one of the constructor(s) has to be called when the object is instantiated - which is the reason the compiler will create a default constructor for you if you omit to add any constructors to your class. But it will be a serious error for your compiler to compile/link the above code without the implementation of your declared constructor, so I will really be surprised if this is the reason for your problem.
But the symptoms you describe definitely sounds like the 'hdr' pointer you are passing to the updateHeader function is invalid. The reason being that the 1st time you are dereferencing this pointer after the updateHeader function call is in the... Hdr->SetCommand(cmd); ...call (which you say crashes).
I can only think of 2 possible scenarios for this invalid pointer:
a.) You have some problem with your heap and the allocation of memory with the 'new' operator failed on creation of the 'hdr' object. Maybe you have insufficient heap space. On some embedded environments you may also need to provide 'custom' versions of the 'new' and 'delete' operator. The easiest way to check this (and you should always do) is to check the validity of the pointer after the allocation:
CHeader* hdr = new CHeader();
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
The normal behaviour when 'new' fails should actually be to throw an exception - so the following code will cater for that as well:
try{
CHeader* hdr = new CHeader();
} catch(...) {
//handle or throw specific exception i.e. AfxThrowMemoryException() for MFC
}
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
}
b.) You are using some older (possibly 16 bit and/or embedded) environment, where you may need to use a FAR pointer (which includes the SEGMENT address) for objects created on the heap.
I suspect that you will need to provide more details of your environment plus compiler to get any useful feedback on this problem.