I have a bunch of *.h files, containing only c-style definitions like
#define ALPHA_REACTOR_CODE 99641
#define BETA_REACTOR_CODE 99642
#define GAMMA_REACTOR_CODE 99643
#define DELTA_REACTOR_CODE 99644
How can I use this files in my С# code without changes and work with this constant in my code?
apologies for the late answer when I promised one earlier.
The idea I have involves using the runtime code compiler as well as reflection to dynamically generate a class that contains all these constants.
So the steps (or pseudocode), as I see it are:
#defineand store these.Microsoft.CSharp.CSharpCodeProvider()and an empty template file, compile a DLL in memory that contains a class that exposespublic const int ALPHA_REACTOR_CODE = 99641;style constants.Assembly.GetType(string)to get the type of your generated classSo if that’s our plan of attack, here is some snippets of code that may help you.
1. Loading the .h files
This is pretty basic file reading, the key trick is to filter your lines by
#defineand then parse to aDictionary<string, int>.This will generate a dictionary of all your definitions. You may want to do a
.Distict()call before the.ToDictionary()just in case there is duplicate definitions.2. Generating the Assembly
This is where you use the
Microsoft.CSharp.CSharpCodeProvider()to generate a in-memory assembly. The trick here is to have a “GenerateCode.cs” file that contains a basic structure for a class. This must be set as a EmbeddedResource, otherwise it will try and be compiled (which won’t work).You’ll note the
{0}, we use that with astring.Formatto insert the constants into the file.Use
assembly.GetManifestResourceStream()to get a stream of this template file and a normalStreamReaderto read this into one big string in memory.Generate the constants by using a
StringBuilderand basicstring.Format()formatting coupled with the Dictionary of values.Then just use string.Format() to insert the builder string into the generated class string (using the
{0})Then, you just need to use the
Microsoft.CSharp.CSharpCodeProvider()to generate an assembly in memory.3 & 4. Using Reflection
now you have an assembly that contains a type with your constants defined in it, you can use
assembly.GetType("GeneratedCode.GeneratedConstants");to get the type, and use Reflection to get the constants out, either one at a time or all together.Have a look at this blog post which covers how to get a const using reflection: http://weblogs.asp.net/whaggard/archive/2003/02/20/2708.aspx
Well I hope that helps you out. It’s not an overly complex solution, but has a few moving parts.
Good luck!