如何测试NULL或NULLPTR的GCROOT参考

How to test gcroot reference for NULL or nullptr?

本文关键字:NULLPTR GCROOT 参考 NULL 何测试 测试      更新时间:2023-10-16

在C /CLI项目中,我在本机C 类中有一种方法,我想检查gcroot参考的NULLnullptr。我该怎么做呢?以下所有内容似乎都没有用:

void Foo::doIt(gcroot<System::String^> aString)
{
    // This seems straightforward, but does not work
    if (aString == nullptr)
    {
        // compiler error C2088: '==': illegal for struct
    }
    // Worth a try, but does not work either
    if (aString == NULL)
    {
        // compiler error C2678: binary '==' : no operator found
        // which takes a left-hand operand of type 'gcroot<T>'
        // (or there is no acceptable conversion)
    }

    // Desperate, but same result as above
    if (aString == gcroot<System::String^>(nullptr))
    {
        // compiler error C2678: binary '==' : no operator found
        // which takes a left-hand operand of type 'gcroot<T>'
        // (or there is no acceptable conversion)
    }
}

编辑

以上只是一个简化的示例。我实际上正在研究一个包装库,该图书馆在托管和本机代码之间"翻译"。我正在研究的类是包裹托管对象的本机C 类。在本机C 类的构造函数中,我获得了我想检查null的gcroot参考。

使用static_castgcroot转换为托管类型,然后将其与nullptr进行比较。

我的测试程序:

int main(array<System::String ^> ^args)
{
    gcroot<System::String^> aString;
    if (static_cast<String^>(aString) == nullptr)
    {
        Debug::WriteLine("aString == nullptr");
    }
    aString = "foo";
    if (static_cast<String^>(aString) != nullptr)
    {
        Debug::WriteLine("aString != nullptr");
    }
    return 0;
}

结果:

挤压== nullptr夸耀!= nullptr

这也有效:

void Foo::doIt(gcroot<System::String^> aString)
{
    if (System::Object::ReferenceEquals(aString, nullptr))
    {
        System::Diagnostics::Debug::WriteLine("aString == nullptr");
    }
}

这是另一个技巧,可能更可读性:

void PrintString(gcroot <System::String^> str)
{
    if (str.operator ->() != nullptr)
    {
        Console::WriteLine("The string is: " + str);
    }
}