XLL+ Class Library (7.0)

Converting to and from .NET types

Helper functions

The XLL+ library contains a set of helper functions to make it simple to convert C++ types to and from managed types.

The functions are in the header xlpclrconvert.h, and are all in the namespace ple::clr. By default, when the XLL+ AppWizard creates a CLR project, the following lines are added to the main cpp source file:

CopyC++
#include <xlpclrconvert.h> 
using namespace ple::clr;

ple::clr::toClr

Use the various versions of toClr(), toClr<T>(), and toClrDate() to convert C++ values passed from Excel into their CLR equivalents.

These functions handle numbers, dates, booleans, strings and arrays. The example below converts a string argument to a .NET string, and an array of strings to a .NET array:

CopyC++
CXlOper* PrefixArray_Impl(CXlOper& xloResult, const CXlStringArg& Prefix, const 
    CXlOper* StringArray_op)
{
    // Input buffers 
    std::vector<CString> StringArray;
    // Validate and translate inputs
    XlReadVector(*StringArray_op, StringArray, L"StringArray", XLA_TRUNC_ONEMPTY
        |XLA_TRUNC_ONBLANK);
    // End of generated code 
//}}XLP_SRC 
    // Create an instance of a .NET class
    MyAssembly::MyClass^ instance = gcnew MyAssembly::MyClass(<i>toClr(Prefix)</i>);
    // Use an instance method of the class, and return the result to Excel.
    xloResult = toXl(instance->AddPrefix(<i>toClr(StringArray)</i>));
    return xloResult.Ret();
}

ple::clr::toXl

Use toXl() and toXl<T>() to convert CLR values to Excel return values.

The various forms of toXl() handle booleans, numbers, integers, dates, strings and arrays of 1 or 2 dimensions.

CopyC++
// Return a CLR array of integers as a vector of numbers 
array<int>^ clrArrayOfInt = SomeClass::SomeMethod();
xloResult = toXl(clrArrayOfInt);

// Return a CLR string
System::String^ clrString = System::DateTime::Now.ToString();
xloResult = toXl(clrString);

// Return a CLR date as a number
System::DateTime clrDate = System::DateTime::Now;
xloResult = toXl(clrDate);

ple::clr::objectToXl

Use objectToXl() to convert CLR values of unknown type to Excel return values.

objectToXl() handles most standard .NET types, either as scalar values or as arrays of 1 or 2 dimensions.

CopyC++
// Return a CLR object of unknown type
System::Object^ oResult = SomeClass::SomeMethod();
xloResult = objectToXl(oResult);

See the ClrDemo and AssemblyDemo samples for examples of the use of toClr() and toXl().

Next: Using WinForms from an add-in >>