简体   繁体   English

是否可以在C ++和C#之间共享“枚举类”?

[英]Is it possible to share an “enum class” between C++ and C#?

I refer to a previous question: Is it possible to share an enum declaration between C# and unmanaged C++? 我指的是上一个问题: 是否可以在C#和非托管C ++之间共享一个枚举声明?

I would like to do something similar, but for an enum class instead of an enum: 我想做类似的事情,但对于枚举类而不是枚举:

C++ code: C ++代码:

enum class MyEnum { ONE, TWO, THREE, ... }

C# code: C#代码:

public enum {ONE, TWO, THREE, ...}

Is there some preprocessor magic that can be done to achieve this? 有一些预处理器魔术可以做到这一点吗? I cant seem to remove the "class" keyword in the C# part of the code. 我似乎无法在代码的C#部分中删除“ class”关键字。

eg: in MyEnum.cs 例如:在MyEnum.cs中

#if __LINE__        // if C++
#define public      // C++ code: removes public keyword for C++
#else
#define class       // does not work: unable to remove the class keyword for C#
#endif



enum class MyEnum { ONE, TWO, THREE, ... }


#if __LINE__
#undef public // ok: remove public = nothing definition in C++
#else
#undef class // does not work: #undef must be at the top of the file in C#
#endif

C# preprocessor is way more limited compared to the C++ preprocessor. 与C ++预处理程序相比,C#预处理程序的局限性更大。 You can leave C# syntax in the source file, and use C++ preprocessor trickery to make it valid C++ code. 您可以在源文件中保留C#语法,并使用C ++预处理程序技巧使其变为有效的C ++代码。 Like this: 像这样:

// enum.cs
public enum MyEnum : int { ONE, TWO, THREE };

And to consume in C++: 并在C ++中使用:

// enum-cpp.h
#define public
#define enum enum struct

#include "enum.cs"

#undef enum
#undef public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM