views:

75

answers:

2

I need an opinion on writing a managed (C#) wrapper for an unmanaged C++ DLL.

Let's say I have an object like this:

public class ManagedObject
{
  public void DoSomethingWithTheObject()
  {

  }
}

and suppose that the DoSomethingWithTheObject() method has to make a call to the unmanaged DLL method.

Now there are two acceptable possibilities that come to my mind:

public void DoSomethingWithTheObject()
{
    DllWrapperClass.DirectCallToUnmanagedMethod(some_value_type);
}

and

public void DoSomethingWithTheObject()
{
    DllWrapperClass.MethodName(this);
}

What I'm basically asking is if

  1. the wrapper class should merely be a wrapper to the unmanaged methods and all objects call those methods directly

  2. the wrapper class should be neatly integrated with the objects and hide as much of the "unmanaged way" of working as possbile

I'm leaning towards the second option, but I'd like to hear some other opinions as both ways have their own pros and cons.

+4  A: 

Option 2. This is one of the principles underlying the .NET Framework itself: to provide a set of managed libraries that are consistent regardless of the shape of the unmanaged APIs they wrap.

Your wrapper should follow the .NET Class Library Design Guidelines as far as possible. You'll know you're on the right track when your managed wrapper starts to feel like pure C# instead of a layer over an unmanaged DLL.

Tim Robinson
Thanks. I had exactly the same thoughts.
Carko
1+. For your better answer.
Aliostad
+1  A: 

As you had figured out, the second option is always preferable but now always possible. Abstracting the unmanaged or unsafe parts is better but sometimes client application has to make decisions or provide many info. In this latter case, you end up writing many classes that only mimic their unmanaged counterparts.

Generally, hide as much as you can.

Aliostad