Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test gcroot reference for NULL or nullptr?

In a C++/CLI project I have a method in a native C++ class where I would like to check a gcroot reference for NULL or nullptr. How do I do this? None of the following seems to work:

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)
    }
}

EDIT

The above is just a simplified example. I am actually working on a wrapper library that "translates" between managed and native code. The class I am working on is a native C++ class that wraps a managed object. In the constructor of the native C++ class I get a gcroot reference which I want to check for null.

like image 633
herzbube Avatar asked Jan 20 '14 16:01

herzbube


2 Answers

Use a static_cast to convert the gcroot to the managed type, and then compare that to nullptr.

My test program:

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;
}

Results:

aString == nullptr
aString != nullptr
like image 53
David Yaw Avatar answered Oct 05 '22 12:10

David Yaw


This also works:

void Foo::doIt(gcroot<System::String^> aString)
{
    if (System::Object::ReferenceEquals(aString, nullptr))
    {
        System::Diagnostics::Debug::WriteLine("aString == nullptr");
    }
}
like image 25
herzbube Avatar answered Oct 05 '22 11:10

herzbube