简体   繁体   中英

C# wrapper design for DLL with P/Invoke

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM