[英]Accessing C++ class enum values from C#
I am trying to access an enum in a C++ class header (.h) from C#. 我正在尝试从C#访问C ++类头(.h)中的枚举。 Is there a simple way of doing this?
有一个简单的方法吗? Every example I have seen involves compiling the class into a .dll, which for this example is kind of a waste because the function of this class is pretty limited.
我见过的每个示例都涉及将类编译成.dll,对于该示例而言,这是一种浪费,因为此类的功能非常有限。
Edit by request: The C++ library CAN be modified. 根据要求编辑:可以修改C ++库。 In fact, the C++ library is the major component of the project(firmware) and is developed by other members of my team, the C# (my part) is just for unit testing purposes.
实际上,C ++库是项目(固件)的主要组成部分,是由我团队的其他成员开发的,C#(我的部分)仅用于单元测试。
Realistically, you have three options: 实际上,您有三个选择:
extern "C"
) that includes this header and returns the enum value you are interested in, then P/Invoke this library from C#. extern "C"
)并返回您感兴趣的枚举值,然后从C#中P /调用此库。 为了访问C ++枚举,您必须将C ++类转换为.NET可以识别的内容,这意味着将其编译为C ++ / CLI(如果可以选择)或转换为.NET互操作性可以的DLL。访问。
Well, this freaks the CS pre-compiler out a bit, but it builds: 好吧,这让CS预编译器有些吃惊,但它建立了:
#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. 只需将条件编译符号
CSHARP
添加到您的C#项目中,将现有的.cs文件和预处理器定义CPP
到您的C ++项目中。
(credit to Yakk for having the same idea) (由于具有相同的想法而致谢Yakk)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.