MATLAB: How to pass arguments in C++ to a function with a VARARGIN signature that has been compiled to a Generic COM Component using MATLAB Builder NE

MATLAB Builder NE

I have a MATLAB program that expects a VARARGIN as an input. I have compiled the function as a Generic COM Component, but I don't know how to pass the arguments in a C++ project.

Best Answer

When a MATLAB function with a formal parameter of type VARARGIN is compiled to a Generic COM Component, the corresponding formal parameter of the compiled component is of type VARIANT.
In order to pass the actual arguments, you can create a SAFEARRAY of VARIANTs containing the arguments of different types and then store it in a variable of type VARIANT that will be accepted and interpreted correctly by the component, as follows:
// Declare variables.
VARIANT in, * inArray;
// Create SAFEARRAY of VARIANTs.
int cEntries = 4;
SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
// Lock the SAFEARRAY and get a pointer to the VARIANT elements.
SafeArrayAccessData(psa, (void **)&inArray);
// Populate the SAFEARRAY with the actual arguments.
// Set string value:
V_BSTR(&inArray[0]) = SysAllocString(L"String argument 1");
V_VT(&inArray[0]) = VT_BSTR;
// Set another string value in a different way:
inArray[1].bstrVal = SysAllocString(L"String argument 2");
inArray[1].vt = VT_BSTR;
// Set double value:
V_R8(&inArray[2]) = 1.2;
V_VT(&inArray[2]) = VT_R8;
// Set another double value in a different way:
inArray[3].dblVal = 1.3;
inArray[3].vt = VT_R8;
// Decrement SAFEARRAY lock.
SafeArrayUnaccessData(psa);
// Set VARIANT type and store SAFEARRAY in it.
// The following two lines are equivalent.
V_VT() = VT_ARRAY | VT_VARIANT;
// in.vt = VT_ARRAY | VT_VARIANT;
// The following three lines are equivalent.
V_ARRAY() = psa;
//in.parray = psa;
//in.byref = psa;
// Call Generic COM Component and pass the variable "in".
// [...]
// Dispose off SAFEARRAY.
SafeArrayDestroy(psa);
For related information, please see:
SAFEARRAY Data Type
VARIANT and VARIANTARG
Handling COM Data in MATLAB Software