// -----------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using ExcelDna.Utilities;
namespace ObjectHandles
{
public static class HandleTestFunctions
{
// Alternative is to make everything in ObjectHandler stat
static ObjectHandler _objectHandler = new ObjectHandler();
public static object TestHandleSample()
{
return "Hello from ObjectHandles!";
}
// A sample function that returns a handle
// (either the handle for the existing object of the given type and parameters, or a new one).
public static object MatrixCreate(int rows, int cols)
{
// The first argument to GetHandle will identify the handle type, and will also be used in the created handle itself.
// We use the input parameters ('rows' and 'columns' here) in two different ways:
// 1. to distinguish different calls to the ObjectHandler.GetHandle, which accordingly decides whether to make a new handle or not
// 2. as captured locals in the delegate passed for the createObject parameter, used when a new object must be made.
return _objectHandler.GetHandle("Matrix", new object[] { rows, cols }, () => MatrixCreateImpl(rows, cols));
}
// A sample function that takes a handle, and uses the object behind it.
public static object MatrixEntry(string matrixHandle, int row, int col)
{
object value;
if (_objectHandler.TryGetObject(matrixHandle, out value))
{
double[,] matrix = (double[,])value;
return matrix[row, col];
}
// No object for the handle ...
return "!!! INVALID HANDLE";
}
// Creates a rows * cols matrix with entries like 1.02 for row 1, col 2
private static object MatrixCreateImpl(int rows, int cols)
{
double[,] matrix = new double[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i, j] = i + j / 100.0;
}
}
return matrix;
}
}
}