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

后端 未结 5 2180
鱼传尺愫
鱼传尺愫 2020-12-16 21:18

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

5条回答
  •  情书的邮戳
    2020-12-16 22:00

    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 
    const double ACCELERATION_DUE_TO_GRAVITY = 9.8;
    int main()
    {
         std::cout << "Acceleration due to gravity is: " << 
             ACCELERATION_DUE_TO_GRAVITY;
    }
    

    becomes

    #include 
    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#.

提交回复
热议问题