Reuse define statement from .h file in C# code

前端 未结 7 1977
广开言路
广开言路 2021-01-18 14:08

I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is th

7条回答
  •  没有蜡笔的小新
    2021-01-18 14:16

    Building on gbjbaanb's solution, I created a .tt file that finds all .h files in a specific directory and rolls them into a .cs file with multiple classes.

    Differences

    • I added support for doubles
    • Switched from try-catch to TryParse
    • Reads multiple .h files
    • Uses 'readonly' instead of 'const'
    • Trims #define lines that end in ;
    • Namespace is set based on .tt location in project

    <#@ template language="C#" hostspecific="True" debug="True" #>
    <#@ output extension="cs" #>
    <#@ assembly name="System.Core.dll" #>
    <#@ import namespace="System" #>
    <#@ import namespace="System.Collections.Generic" #>
    <#@ import namespace="System.IO" #>
    <#
    string hPath = Host.ResolveAssemblyReference("$(ProjectDir)") + "ProgramData\\DeltaTau\\";  
    string[] hFiles = System.IO.Directory.GetFiles(hPath, "*.h", System.IO.SearchOption.AllDirectories);
    var namespaceName = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");
    #>
    //------------------------------------------------------------------------------
    //     This code was generated by template for T4
    //     Generated at <#=DateTime.Now#>
    //------------------------------------------------------------------------------
    
    namespace <#=namespaceName#>
    {
    <#foreach (string input_file in hFiles)
    {
    StreamReader defines = new StreamReader(input_file);
    #>
        public class <#=System.IO.Path.GetFileNameWithoutExtension(input_file)#>
        {
    <#    // constants definitions
    
        while (defines.Peek() >= 0)
        {
            string def = defines.ReadLine();
            string[] parts;
            if (def.Length > 3 && def.StartsWith("#define"))
            {
                def = def.TrimEnd(';');
                parts = def.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
                Int32 intVal;
                double dblVal;
                if (Int32.TryParse(parts[2], out intVal))
                {
                #>
            public static readonly int <#=parts[1]#> = <#=parts[2]#>;           
    <#
                }
                else if (Double.TryParse(parts[2], out dblVal))
                {
                #>
            public static readonly double <#=parts[1]#> = <#=parts[2]#>;            
    <#
                }
                else
                {
                #>
            public static readonly string <#=parts[1]#> = "<#=parts[2]#>";
    <#          
                }
            }
        } #>
        }
    <#}#>     
    }
    

提交回复
热议问题