使用 P/Invoke 的 DLL 的 C# 包装器设计
我需要关于为非托管 C++ DLL 编写托管 (C#) 包装器的意见。
假设我有一个像这样的对象:
public class ManagedObject
{
public void DoSomethingWithTheObject()
{
}
}
并假设 DoSomethingWithTheObject() 方法必须调用非托管 DLL 方法。
现在我想到了两种可以接受的可能性:
public void DoSomethingWithTheObject()
{
DllWrapperClass.DirectCallToUnmanagedMethod(some_value_type);
}
包装
public void DoSomethingWithTheObject()
{
DllWrapperClass.MethodName(this);
}
我基本上要问的是,
- 类是否应该仅仅是非托管方法的包装,并且所有对象都直接调用这些方法
包装器类应该与对象巧妙地集成,并尽可能多地隐藏工作的“非托管方式”
我倾向于第二种选择,但我想听听其他一些意见,因为这两种方式都有自己的优点和缺点。
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
the wrapper class should merely be a wrapper to the unmanaged methods and all objects call those methods directly
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
选项 2。这是 .NET Framework 本身的基本原则之一:提供一组一致的托管库,无论它们包装的非托管 API 的形状如何。
您的包装器应遵循 .NET 类库设计指南可能的。当您的托管包装器开始感觉像纯 C# 而不是非托管 DLL 上的一层时,您就会知道自己走在正确的轨道上。
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.