Search code examples
c#c++dllunmanagedmanaged

How to pass const int from managed C++ DLL to C# for use as field value in an attribute


I have a const int that is computed at compile time in my Managed C++ DLL. I need to use this value in an attribute within the C# program that calls it. Initially I had created a static method that returns the const int value but C# doesn't see this as a compile time const. I also tried declaring it as a const int within the DLL namespace

// C++
namespace MyNameSpace {
    const int AttributeConstValue = 15 + sizeof(int);
 . . .
}

Attempts to access MyNameSpace.AttributeConstValue from C# returns "does not exist in namespace MyNameSpace"

Is there a way to pass a const to C# and have it see it as a const expression?


Solution

  • You must use the C++/CLI literal keyword to declare public constants that are visible to other managed compilers. And it must appear inside a ref class. Like this:

    namespace Example {
        public ref class Constants {
        public:
            literal int AttributeConstValue = 15 + sizeof(int);
        };
    }
    

    Sample C# usage:

    [MyAttribute(Example.Constants.AttributeConstValue)]
    // etc..
    

    Beware that this is fairly dangerous. The literal value gets compiled into the C# assembly's metadata without a reference to your C++/CLI assembly. So if you make a change to this declaration but don't recompile the C# project then you'll have a nasty mismatch. But as long as you need to use it in an attribute declaration then there's no fix for this.