Blog

Sharing Enums and Constants Between a C# and C++ Project

Shared File

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).

#if WIN32

	// C++ code--removes public keyword for C++
    #define public
	
#else

	// C# code
    using System;
    namespace MyNamespace
    {
		public class SharedEnums
        {
           //... C# Specific class code
		   
#endif

			//These items are members of the shared C# class 
			//and global in C++
			public const int SharedInt = 10000;
    
#if !WIN32

	// C# code
		};   //end of class SharedEnums
		
#endif

    public enum ENUM_MY_ENUM
    {
        VALUE_1,   
        VALUE_2,   
        VALUE_3,     
        VALUE_4
    };

#if WIN32

	//C++ code
	#undef public

#else

	//C# code
	}    // end MyNamespace

#endif

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.

Implementation

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

C++

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.

#ifndef SHARED_ENUMS_H_
#define SHARED_ENUMS_H_

#include "SharedEnums.cs.h"

#endif

C#

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.

Comments

There are currently no comments, be the first to post one.

Post a comment

Name (required)

Email (required)

CAPTCHA image
Enter the code shown above: