Sharing Enums and Constants Between a C# and C++ Project
In a recent DMC project using a combination of C# and C++, it was necessary to share enums and constants defined in one project with the other to guarantee compatibility and reduce errors. This was accomplished through the use of compiler directives and a single shared header file. Below is example code outlining the required format of the shared file which we will refer to as “SharedEnums.cs.h” (note that the .h suffix was used to enable intellisense support on the C++ side).
// C++ code--removes public keyword for C++
// C# code
public class SharedEnums
//... C# Specific class code
//These items are members of the shared C# class
//and global in C++
public const int SharedInt = 10000;
// C# code
}; //end of class SharedEnums
public enum ENUM_MY_ENUM
} // end MyNamespace
In the header we use the #if WIN32 to differentiate between whether this code is being compiled in the C++ project or the C# project. This allows us to separate out the C# and C++ specific parts of the file while leaving the shared definitions for the constants and enums. It was also necessary to temporarily remove the public keyword from C++ by using the #define public and #undef public statements.
Once we have defined our shared header file, all that is left is to implement it into both the C# and C++ projects. Inclusion of the file in both projects could be done manually, or if source control is used through external reference. Once included in the projects, the file must be properly integrated into the build
On the C++ side, the easiest way to integrate the shared header file is to create an additional file (example: SharedEnums.h) that includes the shared file and allows you to use standard header file include guards. This file can then be included in any file needing the global shared enum definitions.
On the C# the only thing necessary is to ensure that the SharedEnums.cs.h file is properly compiled since we used a *.h suffix to enable C++ intellisense. Compiling a non *.cs file can be accomplished by going to the properties of that file and setting the build option to compile.
Learn more about DMC's software and web development services.
There are currently no comments, be the first to post one.