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

后端 未结 5 2174
鱼传尺愫
鱼传尺愫 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 21:45

    You can create a separate C++/CLI project and define all your constants in a .h file. For example, create C++/CLI Class Library project called "ConstantBridge" and a C# project called "CSharpProgram":

    Constants.h

    namespace Constants
    {
        const int MAGIC_NUMBER = 42;
    }
    
    // String literals must be defined as macros
    #define MAGIC_PHRASE "Hello World"
    
    // Since stirngs must be macros it's arguably more consistent 
    // to use `define` throughout. This is for demonstration purpose.
    

    ConstantBridge.h

    #include "Constants.h"
    
    namespace ConstantBridge { public ref class ConstantBridge {
    public:
        // The use of the `literal` keyword is important
        // `static const` will not work
        literal int kMagicNumber = Constants::MAGIC_NUMBER;
        literal String ^ kMagicPhrase = MAGIC_PHRASE;
    };}
    

    CSharpProgram.cs

    Console.WriteLine(ConstantBridge.kMagicNumber); // "42"
    Console.WriteLine(ConstantBridge.kMagicPhrase); // "Hello World"
    

    Now, have the "CSharpProgram" project reference the "ConstantBridge" project. Your other native C++ projects can simply #include "Constants.h".

    As long as you reference only literals from the ConstantBridge project, a runtime dependency will not be generated. You can verify using ILSpy or ILdasm. const in C# and literal in C++/CLI are copied "literally" to the call site during compilation.

提交回复
热议问题