Asad Iqbal
Asad Iqbal

Reputation: 304

how to read constants from .h file in C#

I want to read the constants in C#, these constants are defined in a .h file for C++. Can anyone tell me how to perform this in C# ? The C++ .h file looks like:

#define MYSTRING1 "6.9.24 (32 bit)"
#define MYSTRING2 "6.8.24 (32 bit)"

I want to read this in C# ?

Upvotes: 1

Views: 2464

Answers (2)

A.R.
A.R.

Reputation: 15704

Here is a really simple answer that you can use on each line of your .h file to extract the string value.

string GetConstVal(string line)
{
  string[] lineParts = string.Split(line, ' ');
  if (lineParts[0] == "#define")
  {
    return lineParts[2];
  }
  return null;
}

So any time it returns null, you don't have a constant. Now keep in mind that it is only getting the value of the constant, not the name, but you can easily modify the code to return that as well via out parameter, etc.

If you want to represent other data types, like integers, etc. you will have to think of something clever since macros in C++ don't really count as type safe.

Upvotes: 1

Yousf
Yousf

Reputation: 3997

You have two options:

1- Create a C++ wrapper code, which wraps these macros, export this code to a lib or dll and use it from C#.

2- read/parse the .h file from your code, and get the values at run-time.

Upvotes: 1

Related Questions