c# - 是否可以在 C++ 和 C# 之间共享 "enum class"?

标签 c# c++

我引用了之前的一个问题:Is it possible to share an enum declaration between C# and unmanaged C++?

我想做类似的事情,但对于枚举类而不是枚举:

C++代码:

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

C#代码:

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

是否有一些预处理器魔术可以实现这一目标?我似乎无法删除代码的 C# 部分中的“class”关键字。

例如:在 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++ 预处理器相比,C# 预处理器的局限性更大。您可以在源文件中保留 C# 语法,并使用 C++ 预处理器技巧使其成为有效的 C++ 代码。像这样:

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

并在 C++ 中使用:

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

#include "enum.cs"

#undef enum
#undef public

关于c# - 是否可以在 C++ 和 C# 之间共享 "enum class"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56834416/

相关文章:

c# - 如果我重建我的项目引用的 dll,我是否也必须重建该项目?

c# - 将 LastIndexOf 和 Substring 与数组一起使用

c# - 如何删除未使用的命名空间

c++ - 无法更新 QTableWidget 中的字符串

c++ - header semaphore.h 不能包含 eclipse juno。我收到错误 "unresolved inclusion"

c# - 通过 Options 类或 DesiredCapability 禁用 IE 弹出窗口拦截器

c# - 在 LINQ to Entities 中使用中间实体会导致 System.NotSupportedException

c++ - 双链表出现错误 'pointer being freed was not allocated'

c++ - 使用 Clang 13 的 Ubuntu 20.04 上缺少 C++20 头文件

c++ - "Illegal block entry"以及 yaml-cpp 中的 YAML 怪物示例