我正在尝试从 C# 访问 C++ 类头 (.h) 中的枚举。有没有一种简单的方法可以做到这一点?我看到的每个示例都涉及将类编译为 .dll,这对于本示例来说有点浪费,因为此类的功能非常有限。
按要求编辑:可以修改 C++ 库。事实上,C++ 库是项目(固件)的主要组成部分,由我团队的其他成员开发,C#(我的部分)仅用于单元测试目的。
实际上,您有三个选择:
extern "C"
包含此标头的 C 函数 ( ) 并返回您感兴趣的枚举值的胶水库,然后从 C# 中 P/Invoke 此库。Well, this freaks the CS pre-compiler out a bit, but it builds:
#if CSHARP
namespace Test
{
public enum SharedEnum
#endif //CSHARP
#if CPP
typedef enum SharedEnum
#endif //CPP
{
One,
Two,
Three
}
#if CPP
SharedEnum
#endif //CPP
;
#if CSHARP
};
#endif
Just add the Conditional Compilation symbol CSHARP
to your C# project, add the existing .cs file and the preprocessor definition CPP
to your C++ project.
(credit to Yakk for having the same idea)
为了访问 C++ 枚举,您必须将 C++ 类转换为 .NET 可以识别的东西,这意味着将其编译为 C++/CLI(如果这是一个选项)或转换为 .NET 互操作可以的 DLL使用权。