简体   繁体   English

从C#访问C ++类枚举值

[英]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: 实际上,您有三个选择:

  1. Create a glue library that exports a C function ( extern "C" ) that includes this header and returns the enum value you are interested in, then P/Invoke this library from C#. 创建一个粘合库,该粘合库导出包含此头的C函数( extern "C" )并返回您感兴趣的枚举值,然后从C#中P /调用此库。
  2. Hard-code the value in your C# code. 将值硬编码在C#代码中。
  3. Write a C++ parser and extract the value that way. 编写C ++解析器,然后以这种方式提取值。 (Either a complete C++ parser, which would be preferable, or you can be lazy and write a simple regex parser that will work on this particular version of the C++ header, but might break in the future if the code changes in a way you didn't expect.) (最好是使用完整的C ++解析器,或者您可以懒惰地编写一个简单的regex解析器,该解析器可以在此特定版本的C ++头文件上使用,但是如果代码以您未使用的方式更改,将来可能会中断没想到。)

为了访问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.

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