Search code examples
c#c++interfacecomcom-interop

COM interface declaration and use (or lack thereof)


As I understand it, COM interfaces are abstract classes in C++ but for some reason translate to C# interfaces. Why must one declare all methods of an interface in C#, even when one does not intend to use any of its members? Take for example IFileOperation, I've tried removing function declarations which I have verified are never called in my code but it results in System.AccessViolationException being thrown.


Solution

  • Your code doesn't run in isolation. A COM interface is a binary contract between code offering a service, and code using those services. The contract is an all-or-nothing agreement (with the caveat that E_NOTIMPL can be used to indicate certain optional methods are not available, if the interface documentation indicates that this is allowed).

    IFileOperation is not your contract. It belongs to Microsoft. It's used to interact with Microsoft code and other 3rd party code. That code (which you don't own) expects classes implementing the interface to provide a function pointer for each method in the interface (and put it in a VTable). That's what the interface means. You don't get to not provide that function pointer. And that code will call any method in the interface it sees fit to call, according to the documented rules of the interface. It's not your choice.

    If you are absolutely sure the method is not called it means you're not using it to interact with the shell. If you don't like some of the methods and you don't interact with the shell (or other 3rd party code) you can always make up your own interface; nobody forces you to borrow someone else's. Make sure both the COM server and Client agree on the interface definition.

    On the other hand, if you are interacting with the shell, you don't know which methods the shell will call on you. You have to provide implementations for all of them, even if all you do is return an error. I'm not super-familiar with IFileOperation so read the documentation carefully. It's possible that some methods can return specific error messages (like E_NOTIMPL) to indicate the specific functionality is not available.

    The fact that you are getting an invalid access violation strongly suggests one of those methods you dislike is indeed being called.