c++ - 将 null 从 C++/CLI 发送到托管 C#

标签 c++ visual-c++ enums clr nullable

我有一个 C++/CLI 包装器可以调用 C# 代码。在 C# 代码中,我有一个方法接受一个可为 null 的枚举作为参数,但我不知道如何从我的包装器中使用一个 null 参数调用这个方法。

C# 方法:

public int DoSomething(MyEnum? option)
{
    if (option != null)
        //Do something
    else
        //Do something else 
}

调用 DoSomething() 的 C++ 函数:

int MyMethod(int option)
{
    int myVal;
    if (option > -1)
    {
        myVal = component->DoSomething((CSharpNameSpace::MyEnum)option); //This works
    }
    else
    {
        myVal = component->DoSomething(??); //I want to send null here
    }
}

我尝试了几件事,但到目前为止没有任何效果:

  • 发送 0、NULL 或 nullptr 将无法编译
  • (CSharpNameSpace::MyEnum)NULL 当然是将值设置为 0

我无法控制 C# 代码,因此无法将枚举更改为无值或类似值。

最佳答案

可空类型在 C++/CLI 中没有得到任何语法支持,这与 C# 非常不同。您遇到的基本障碍是没有从 nullptr 到 Nullable 的隐式转换。一种简单的方法是依赖默认构造函数:

int MyMethod(int option)
{
    Nullable<ClassLibrary1::MyEnum> enu;
    if (option > -1) enu = safe_cast<ClassLibrary1::MyEnum>(option);
    return component->DoSomething(enu);
}

关于c++ - 将 null 从 C++/CLI 发送到托管 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39291234/

相关文章:

c++ - Visual C++ 14 - 无法构建基于 Visual C++ 12 的简单线程程序

swift - 需要澄清Swift中的枚举类型

c++ - 期待 eof 但 eof 附近的任意数据

C++按: hasNextLine?行读取文件

c++ - 为 boost::deque 保留 block 分配器?

java - 元素周期表的数据结构

c# - 有没有一种简单的方法可以在Flags中写入以2为底的数字?

c++ - 删除 Tesseract 中的处理日志

c++ - C/C++ 字符串文字中的未知元字符?

c++ - 出于测试目的故意让 C++ 程序运行得更慢?