Pergunta

How do you cast a COM interface pointer to void pointer and then back to the COM pointer? Here is some code to illustrate my problem. It's very similar to this sample code: _com_ptr_t assignment in VC++

CoInitialize(NULL);

COMLib::ICalcPtr pCalc = COMLib::ICalcPtr("MyLibrary.Calculator");

pCalc->doSomething();

CoUninitialize();
return 0;

Now, if I were to cast the pCalc object to void*, how would I cast it back to COMLib::ICalcPtr? For example, the second line in the following code gives me a compile error 'QueryInterface' : is not a member of 'System::Void'. Obviously, it's trying to call IUknown.QueryInterface() on the object. Preferably I would like to do this without creating a new interface (hence, without implicitly calling QueryInterface and AddRef).

void *test = pCalc;
COMLib::ICalcPtr pCalc2 = test;//'QueryInterface' : is not a member of 'System::Void'

FYI, the reason I'm doing this is that the object is going to be passed around from java to jni VC++ code as a void* type. I'm open to any suggestion on what to do or what is going on behind the scene.

Foi útil?

Solução

Same way you pass any other opaque structure that either doesn't fit in a pointer or doesn't convert easily: by passing its address.

void* test = new COMLib::ICalcPtr(pCalc);

...

COMLib::ICalcPtr pCalc2 = *(COMLib::ICalcPtr*)test;
delete (COMLib::ICalcPtr*)test;

This will result in calls to AddRef and Release, but not QueryInterface.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top