0

I've got a C# class:

public class MyManagedClass
{
  public ManagedEnum EnumValue {get; set;}
}

which uses the C# enum

public enum ManagedEnum
{
  Enum1,
  Enum2
}

This is accessed by a C++/CLI wrapper class and enum:

enum NativeEnum
{
  Enum1,
  Enum2
};

class WrapperClass
{
public:
  WrapperClass(ManagedNamespace::MyManagedClass^ inManaged):
    _Managed(inManaged)
  {}

  NativeEnum GetEnumValue()
  {
    return (NativeEnum)_Managed->EnumValue;
  }

private:
    gcroot<ManagedNamespace::MyManagedClass^> _Managed;
};

Now, as long as the C# class and C# enum are in the same assembly, this works fine.

But if the C# enum is in a different C# assembly, the C# class still builds fine, but trying to compile the C++ class yields the error:

error C2440: 'type cast' : cannot convert from 'OtherNamespace::ManagedEnum' to 'OtherNamespace::NativeEnum'
1>          Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast

2 Answers 2

1

Try deriving the underlying value, then cast to the native enum.

This is a crude way of doing it, but may be sufficient in your case.

NativeEnum someMethod(ManagedEnum myEnum)
{
  return (NativeEnum)(int)myEnum;
}

Another way is to create a native template method taking both types and the managed enum input, and returning the native type. In such a case, you would have to use reflection to ascertain the underlying type of the managed enum.

Sign up to request clarification or add additional context in comments.

3 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
Sorry, I am new to posting here and was editing the post as you were commenting on it...
Is your judgement because of how I worded the original sentence?
1

In trying out Aaron P's answer, I discovered that the problem was that my C++ project didn't have the C# assembly with the enums in it as a reference. Once I added that reference, it all worked fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.