C#中的字符串和C++/CLI中的String ^ ...如何传递"null"?

use*_*838 3 c# c++ string c++-cli argumentnullexception

我有一些C++库.我还得到了C++/CLI包装器,以便在C#代码中调用来自该库的方法.

假设我想在C#中使用一些调用,如下所示:

string date = MyWrapper.GetValue("SystemSettings", "BuildDate", null);
Run Code Online (Sandbox Code Playgroud)

它将在C++/CLI上调用next函数:

static String^ GetValue(String^ section, String^ key, String^ defaultValue)
Run Code Online (Sandbox Code Playgroud)

我的问题:我有下一个ArgumentNullException:

值不能为null.\ r \nParameter name:managedString.

所以...问题:我应该如何null正确传递?谢谢.

Dav*_*nan 9

传递null的代码很好.问题是你的包装器代码需要检测null并处理它.该代码可能是在假设第三个参数永远不为空的情况下编写的.如果您希望允许null,则必须显式处理该条件:

static String^ GetValue(String^ section, String^ key, String^ defaultValue)
{
    if (defaultValue == nullptr)
        // special case handling
    ....
}
Run Code Online (Sandbox Code Playgroud)