65.9K
CodeProject is changing. Read more.
Home

Moderately Complicated Windows C API in C#, using NtmsApi (RSM) from C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (4 votes)

May 31, 2008

CPOL

2 min read

viewsIcon

18531

downloadIcon

96

Here is some code to serve as both an example "DllImport" beyond some of the trivial cases (I had trouble finding examples), and perhaps as a starting point for anyone else who might be using the RSM (aka NTMS).

Introduction

If you are struggling with the DllImport of Windows functions from DLLs, or from other existing DLLs, this might give you another working example to more forward. Or more specifically, if you are trying to use the functions in NtmsApi.h and NtmsApi.dll, then here are some of the functions I used in a tool I had to create recently.

Background

In Windows 2000, Microsoft introduced a new collection of API functions for managing removable media, like tapes, and for interacting with tape-library/robotic devices. For all the gory details, have a look in the MSDN.

Using the Code

There is no rocket-science/gene-splicing going on in the class interfaces, so using or extending it all should not be too hard. To list all the media pool names in the "root" of the RSM, you could try something like the code below.

//
// A very simple example of using the code
//
string host = @"MyHostDnsName";
string application = @"MyApplication";
NtmsApi.RsmApi rsm = new NtmsApi.RsmApi(host, application);
if (rsm.IsSessionValid)
{
    System.Guid containerPool = Guid.Empty;
    MediaPoolInfo[] poolInfo;
    int rc = rsm.GetMediaPoolInformation(containerPool, out poolInfo);
    foreach (MediaPoolInfo info in poolInfo)
    {
        System.Console.WriteLine(info.Name);
    }
}

Points of Interest

The key lessons I nailed down in the code provided amount to:

  1. C/C++ unions are bad news if you try to map these into a C# struct, particularly if the struct has a mix of value and reference types. So rather than overlap fields using the "explicit layout", create other structs. You will note that I overloaded the GetNtmsObjectInformation several times with different DllImport declarations for the different structs.
  2. I could have saved myself some time if I had been able to find other examples of complicated struct layouts, like the ones here that marshall arrays of bytes and strings.
  3. I had a hard time getting some of the initial details of interacting with the RSM/NTMS working, e.g. creating a session and getting a handle was not bad, but passing a NULL in some cases took a bit of experimentation. Hopefully this will save SomeOneElse(tm) a few days of head scratching.

History

  • v1.0 - May 2008 - Initial release