i was wondering if there is other ways to pass null parameters from c# to c++ with combinations using pinvoke.
consider the following codes where each parameters can be null.
c++
bool Range(const int id, double *rangeT0, double *rangeTW, double *rangeV0, double *rangeVW);
c# counterpart
[DllImport(myDLL)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool Range(int id, IntPtr rangeT0, IntPtr rangeTW, IntPtr rangeV0, IntPtr rangeVW);
I used IntPtr to be able to pass IntPtr.Zero for c++ null. i already considered using overloaded DllImports but having multiple combinations would mean an overload for each null parameter.
so far i came up with this code. it is running but i think its quite too much for a wrapper.
public static bool RangeWrapper (int id, ref double? rangeT0, ref double? rangeTW, ref double? rangeV0, ref double? rangeVW)
{
double[] t0Temp = new double[1];
double[] twTemp = new double[1];
double[] v0Temp = new double[1];
double[] vwTemp = new double[1];
IntPtr rangeT0Ptr = rangeT0 == null ? IntPtr.Zero : Marshal.AllocHGlobal(sizeof(double));
IntPtr rangeTWPtr = rangeTW == null ? IntPtr.Zero : Marshal.AllocHGlobal(sizeof(double));
IntPtr rangeV0Ptr = rangeV0 == null ? IntPtr.Zero : Marshal.AllocHGlobal(sizeof(double));
IntPtr rangeVWPtr = rangeVW == null ? IntPtr.Zero : Marshal.AllocHGlobal(sizeof(double));
if (rangeT0.HasValue)
{
t0Temp[0] = rangeT0.Value;
Marshal.Copy(t0Temp, 0, rangeT0Ptr, 1);
}
if (rangeTW.HasValue)
{
twTemp[0] = rangeTW.Value;
Marshal.Copy(twTemp, 0, rangeTWPtr, 1);
}
if (rangeV0.HasValue)
{
v0Temp[0] = rangeV0.Value;
Marshal.Copy(v0Temp, 0, rangeV0Ptr, 1);
}
if (rangeVW.HasValue)
{
vwTemp[0] = rangeVW.Value;
Marshal.Copy(vwTemp, 0, rangeVWPtr, 1);
}
bool isSuccessful = Range(sigID, rangeT0Ptr, rangeTWPtr, rangeV0Ptr, rangeVWPtr);
if (rangeT0Ptr != IntPtr.Zero)
{
Marshal.Copy(rangeT0Ptr, t0Temp, 0, 1);
rangeT0 = t0Temp[0];
}
else
{
rangeT0 = null;
}
if (rangeTWPtr != IntPtr.Zero)
{
Marshal.Copy(rangeTWPtr, twTemp, 0, 1);
rangeTW = twTemp[0];
}
else
{
rangeTW = null;
}
if (rangeV0Ptr != IntPtr.Zero)
{
Marshal.Copy(rangeV0Ptr, v0Temp, 0, 1);
rangeV0 = v0Temp[0];
}
else
{
rangeV0 = null;
}
if (rangeVWPtr != IntPtr.Zero)
{
Marshal.Copy(rangeVWPtr, vwTemp, 0, 1);
rangeVW = vwTemp[0];
}
else
{
rangeVW = null;
}
Marshal.FreeHGlobal(rangeT0Ptr);
Marshal.FreeHGlobal(rangeTWPtr);
Marshal.FreeHGlobal(rangeV0Ptr);
Marshal.FreeHGlobal(rangeVWPtr);
return isSuccessful;
}
So my question is, is there any other way to pass multiple nullable parameters without making any changes in the native c++ code?