Severus Snape Severus Snape - 3 months ago 32
C++ Question

Sending null from C++/CLI to managed C#

I have a C++/CLI wrapper to be able to call C# code. In the C# code I have a method which accepts a nullable enum as parameter, but I can't figure out how I can call this method with a null parameter from my wrapper.

C# method:

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


The C++ function calling DoSomething():

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


I tried several things but nothing has worked so far:


  • Sending 0, NULL, or nullptr won't compile

  • (CSharpNameSpace::MyEnum)NULL is setting the value to 0 of course



I don't have control of the C# code, so I can't change the enum to have a none value or anything like that.

Answer

Nullable types don't get any syntax love in C++/CLI, very unlike C#. The basic obstacle you run into is that there is no implicit conversion from nullptr to Nullable. A simple way is to rely on the default constructor:

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