Search code examples
c#c++idlmaintainability

How do I share a constant between C# and C++ code?


I'm writing two processes using C# and WCF for one and C++ and WWSAPI for the second. I want to be able to define the address being used for communication between the two in a single place and have both C# and C++ use it. Is this possible?

The closest I've come is defining the constant in an IDL, then using MIDL and TLBIMP to get it into a DLL that can be consumed by C#. However this doesn't seem to expose the constant, or at least I can't figure out how to make it do so. Maybe it is limited to type definitions only.

Any other suggestions?


Solution

  • C# and C++ have differing models for constants. Typically, the constant won't even be emitted in the resulting C++ binary -- it's automatically replaced where it is needed most of the time.

    Rather than using the constant, make a function which returns the constant, which you can P/Invoke from C#.

    Thus,

    #include <iostream>
    const double ACCELERATION_DUE_TO_GRAVITY = 9.8;
    int main()
    {
         std::cout << "Acceleration due to gravity is: " << 
             ACCELERATION_DUE_TO_GRAVITY;
    }
    

    becomes

    #include <iostream>
    extern "C" double AccelerationDueToGravity()
    {
        return 9.8;
    }
    int main()
    {
         std::cout << "Acceleration due to gravity is: " << 
             AccelerationDueToGravity();
    }
    

    which you should be able to P/Invoke from C#.