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

后端 未结 5 2184
鱼传尺愫
鱼传尺愫 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

    When I've had to do that stuff in the past, I've simply added an extra pre-compilation step to the build process which automagically creates one file from another.

    Since your constants will probably be within a class in C#, you can use that as the source file:

    MyClass.cs:
        class MyClass {
            public const int NUM_MONTHS = 12;    //COMMON
            public const int YEAR_BASE = 1900;   //COMMON
        }
    
    grep '//COMMON' MyClass.cs
        | sed -e 's/^ *public const [a-z][a-z]*/#define/'
              -e 's/ *= */ /'
              -e 's/;.*$//'
        >MyClass.h
    grep '//COMMON' MyClass.cs | sed -e 's/ *public //' -e 's/;.*$/;/' >MyClass.hpp
    

    This will give you:

    MyClass.h:
        #define NUM_MONTHS 12
        #define YEAR_BASE 1900
    
    MyClass.hpp:
        const int NUM_MONTHS = 12;
        const int YEAR_BASE = 1900;
    

    Now, getting Visual Studio to perform that step is not something I know how to do. You'll have to investigate whether or not it's even possible. The UNIXy text processing tools are really worth downloading. I have CygWin installed on a few boxes but, for something this localised, you could get away with individual GnuWin32 packages.

    You could probably do a similar job in PowerShell but I'm not really well versed in that.


    Now that's a bit of a kludge so may I suggest a possibly better way for you particular question. Don't use a constant at all. Put the address into a configuration file and have your C# and C++ code read it at startup.

    That way, you get to share the value painlessly and it's configurable in case you ever want to change it in future.

提交回复
热议问题