简体   繁体   English

具有P / Invoke的DLL的C#包装器设计

[英]C# wrapper design for DLL with P/Invoke

I need an opinion on writing a managed (C#) wrapper for an unmanaged C++ DLL. 我需要为非托管C ++ DLL编写托管(C#)包装程序。

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. 并假定DoSomethingWithTheObject()方法必须调用非托管DLL方法。

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 wrapper类应该只是非托管方法的包装,并且所有对象都直接调用这些方法

  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. 选项2。这是.NET Framework本身的基本原则之一:提供一组托管库,这些托管库是一致的,而不管它们包装的非托管API的形状如何。

Your wrapper should follow the .NET Class Library Design Guidelines as far as possible. 包装程序应尽可能遵循.NET类库设计准则 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. 当托管包装器开始感觉像纯C#而不是非托管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. 通常,请尽量隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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