4

Is it possible to call the parameterized constructor with COM? I am going to create an instance of C# class which has parameterized constructor with COM. Now it raises the Memory Excpetion. so I am not sure about instantiation of C# class carrying the parameterized constructor with COM. So Please let me know about the same.

My C# constructor is

public GetNumberFromClass(NumberClass number)
{
}

C++ Constructor:

NumberFromC#::NumberFromC#
{
    getNumberFromClassPtr.CreateInstance(__uuidof(GetNumberFromClass));
}

and the pointer getNumberFromClassPtr throws memory exception as it comes NULL .

Medinoc
  • 6,577
  • 20
  • 42

1 Answers1

3

That's not possible, COM doesn't have a mechanism to pass arguments to a constructor. This is most visible in your C++ snippet, you specified the GUID of the class with the __uuidof keyword as required but you didn't pass a NumberClass argument. You can't.

What goes wrong next is that you didn't check for an error, CreateInstance() returns an HRESULT. Which would have told you that the method failed. The embedded interface pointer is still NULL and that's going to blow your program with an access violation when you just keep motoring on.

Start fixing this by first getting rid of that constructor in your C# class, it must have a default constructor to be usable by COM. Add a property of type NumberClass so you can set that value after the object is created. And of course improve the error handling in your C++ code, these kind of failures just become completely undiagnosable if you don't have any. You must check the return value of CreateInstance() and you must add try/catch blocks in the code that uses the object so you can catch the _com_error exceptions that will be thrown when a method call fails.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Well, that's not the only solution. He could use a class factory that would have a creator method that could accept any parameters. – sharptooth Oct 10 '13 at 10:27
  • Thanks for the Reply.Could you please tell me the example or link related to class factory creator method.So I would implement it in my code as early as possible – SkoolBoyAtWork Oct 10 '13 at 11:38
  • You can make your C++ code look any way you like, writing a little helper function that calls CreateInstance() and then sets the property is boilerplate. It doesn't otherwise have anything to do with your question. – Hans Passant Oct 10 '13 at 11:45