我在 cs 文件中有以下代码(在 Visual Srudio 中编译)
#if __cplusplus
// C++ region, hide the private C# key word "private" from C++
#define private
namespace fastmapping
{
#else
// C# region, namespace and class so the C++ enum would not be the same in C#
namespace Interface
{
public static class Example
{
#endif
// Common part to both C# and C++ (in C++ the private keyword is omitted by define)
private enum GatedMode
{
GATED_MODE,
NON_GATED_MODE
};
// other enums
}
}
Run Code Online (Sandbox Code Playgroud)
C++ 如何使用这个枚举?在 CLI 中?
这里的“技巧”是这不仅仅是一个 C# 文件。
它可能有一个.cs扩展,但它被“巧妙地”编写为既是有效的 C++ 又是有效的 C#,使用#if指令(在两种语言中都存在,但只__cplusplus在前者中设置)来选择要运行的代码,在哪里代码不同。
因此,当您将它传递给 C++ 编译器时,它是 C++ 源代码;当您将它传递给 C# 编译器时,它是 C# 源代码。这是两个源文件合二为一,碰巧列出了具有相同成员的枚举。
这里没有实际的互操作;只是文字欺骗。
不幸的是,它造成了很大的混乱,并且由于重新定义了关键字而在 C++ 中具有未定义的行为。
PInvoke 是桥接 C++/CLI 和 C# 的正确方法。