Search code examples
c#.netinterfacec++-cli

Making C# compatible interface for C++/CLI managed type


I have some native C/C++ functions for which I'm creating managed wrappers in C++/CLI (Visual Studio 2015).

In particular, one of my managed types looks like this:

public ref class MyClass abstract : public IMyClass
{
public:
    virtual void SomeMethod(ID id);
}

The type ID is defined as:

typedef unsigned long ID;

Due to unit testing purposes, I would like to create compatible interfaces to my wrapper types on a different C# assembly that I want to keep separate from the C++/CLI world, so I made this interface:

public interface IMyClass
{
    void SomeMethod(uint id);
}

When I try to compile the managed C++/CLI assembly I'm getting and error saying that I should provide a suitable implementation for "void SomeMethod(unsigned int)".

I used the type uint on my interface because according to this MSDN documentation, an unsigned long is converted to the managed type System.UInt32 (uint), but it seems like (the opposite) using unsigned long to implement a uint is not possible.

Have any of you had the same problem before? Do you know how to fix this? Is it possible to tell the C++/CLI compiler that my unsigned long should be treated as a uint type?

I can't change the ID definition as it is part of the native library and is used extensively by other functions.


Solution

  • When in doubt, be explicit.

    I recommend that you use System::UInt32 everywhere: when you define the interface type, and when you implement it. This will eliminate any subtle mismatches between the definition & the implementation.

    In C++ land, int and long are distinct types, even if they are the same size. When implementing an interface, the parameter type must match exactly, and it appears that the subtle difference between a 32-bit int and a 32-bit long makes a difference.