mono/CppSharp

How to use a constant defined in a different header

Rashmatash opened this issue · 1 comments

Trying to generate code for two headers:

// Header1.h
static const int MAX_NUMBER = 37;

And

//Header2.h
#include "Header1.h"
static const int someNumber = MAX_NUMBER;

The generated code is

public unsafe partial class Header1
{
  // ... internal stuff
   public const int MAX_NUMBER = 37;
}

public unsafe partial class Header2
{
 // ... internal stuff
   public const int someNumber = MAX_NUMBER; // compile error. Should be Header1.MaxNumber, obviously.
}

How does one go about solving this issue?

Also is it possible to tell CppSharp to only generate data declarations without all the interop/internal code? I just want to convert POD structs and enums from C/C++ to their equivalent in C#.

tritao commented

The code that handles this is:

https://github.com/mono/CppSharp/blob/main/src/Generator/Generators/CSharp/CSharpSources.cs#L1627
https://github.com/mono/CppSharp/blob/main/src/CppParser/Parser.cpp#L3509

Ideally we would migrate the native parser out of AST::ExpressionObsolete for variable initializers, which has the name suggests is the old obsolete expression representation for expressions, and would use AST::Expr instead via https://github.com/mono/CppSharp/blob/main/src/CppParser/ParseExpr.cpp#L16.

The easiest fix would be to change the existing code to evaluate this a bit more smartly:
https://github.com/mono/CppSharp/blob/main/src/CppParser/Parser.cpp#L3820

I am not sure the exactly code path that is being taken here in that code, but it could be modified to just evaluate this down to 37 directly in the native code, so no reference to Header1 is needed in generation.

With some of the evaluate functions here: https://clang.llvm.org/doxygen/classclang_1_1Expr.html