Excel RTD Servers: C# without the Excel Assembly Reference

In the description of a minimal C# implementation I suggested you simply reference the “Microsoft Excel Object Library” to get the definition of IRtdServer. Of course this introduces an unnecessary reference and can be problematic. This assembly ends up being tied to a particular version of Excel even though the COM interfaces for the RTD server remains the same. As we’ve seen in the C++ implementation, there’s no reason to have a hard reference to any Excel binaries and we can define all of the interfaces ourselves.

Rather that rely on Excel’s type library for the definitions you can define them yourself. Earlier in this series I showed you what the interfaces look like in C# but they weren’t usable on their own. The trick is that you need to tell the CLR how to marshal some of the more interesting parameters. Of course now that we’ve worked through a minimal C++ implementation you should be quite comfortable with the underlying types as seen by COM and Excel.

So it’s just a matter of using the MarshalAs attribute to tell the CLR how to marshal those multi-dimensional arrays. Specifically, they need to be marshaled as safe arrays of variants. Here’s what it looks like:

public interface IRTDUpdateEvent
    void UpdateNotify();

    int HeartbeatInterval { get; set; }

    void Disconnect();

public interface IRtdServer
    int ServerStart(IRTDUpdateEvent callback);

    object ConnectData(int topicId,
                       [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array strings,
                       ref bool newValues);

    [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]
    Array RefreshData(ref int topicCount);

    void DisconnectData(int topicId);

    int Heartbeat();

    void ServerTerminate();

You can now remove the Excel references and simplify your deployment overall.

If you’re looking for one of my previous articles here is a complete list of them for you to browse through.

Produce the highest quality screenshots with the least amount of effort! Use Window Clippings.

No Comments