0

Is it possible to assign the Interface pointer to another interface pointer where both interface pointers point to same class. below is my code for Test.h and Test.cpp

class Test
    {
        ITestPtr testPtr;
        ITestSecondPtr secondPtr;
    };

 Test:: Test()
    {
    testPtr.CreateInstance(__uuidof(MyNamespace::MyClass));
    secondPtr=testPtr;
    }

Here my ITestPtr and ITestSecondPtr points to same C# class MyClass. So to avoid double initilaization of C# class, I assigned testPtr to secondPtr. It is build successfully. But the Runtime throws the Access Violation Excpeption. Please let me know if any solution.

harper
  • 13,345
  • 8
  • 56
  • 105
  • 3
    `testPtr.QueryInterface(&secondPtr);`, at least thats how you could do this in C++ using the `comdef` smart interface wrapper library from MS. What language you're doing this in, I have no idea, as you tagged this as C++, yet mentioned only C# in your question. – WhozCraig Oct 24 '13 at 06:18
  • +1 to WhozCraig, that is the way to do it. – AndersK Oct 24 '13 at 07:24
  • @WhozCraig Looks like he uses C++/CLI, and the C# class he mentioned is from a DLL or something. – Idan Arye Oct 24 '13 at 07:25
  • @IDan:thanx for the comment.I am using Com .But testPtr.QueryInterface(&secondPtr); this throws the error . – SkoolBoyAtWork Oct 24 '13 at 07:39

1 Answers1

1

No. It's not possible to assign a pointer to one COM interface to another. When you QueryInterface for IUnknown you will always get the same pointer to the implementing object. But when you query for a specific interface you will get different pointer.

The reason is that the pointer points to the VMT pointer. When you have different inherances fro IUnknown you need different VMTs. That's why QueryInterface must select the correct VMT at a different address.

The reason for the convetion to return always the same IUnkown pointer is that this allows to check the identity of an object despite you get different pointer for different intefaces.

So your requested solution: Don't (implicitly) cast COM interface pointer. Use QueryInterface() to get the right pointer.

More Details are here.

Community
  • 1
  • 1
harper
  • 13,345
  • 8
  • 56
  • 105