gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:49:14 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com