首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >松耦合NativeMethods

松耦合NativeMethods
EN

Stack Overflow用户
提问于 2011-11-17 07:34:53
回答 2查看 1.2K关注 0票数 3

我需要使用来自C#的本机DLL。DLL公开了我可以通过P/Invoke访问的几个方法,以及几种类型。所有这些代码都在一个标准的NativeMethods类中。为了保持简单,如下所示:

代码语言:javascript
复制
internal static class NativeMethods
{
    [DllImport("Foo.dll", SetLastError = true)]
    internal static extern ErrorCode Bar(ref Baz baz);

    internal enum ErrorCode { None, Foo, Baz,... } 

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    internal struct Baz
    {
        public int Foo;
        public string Bar;
    }
}

为了实现松散耦合,我需要提取一个接口并使用对NativeMethods的调用来实现它:

代码语言:javascript
复制
public interface IFoo
{
    void Bar(ref Baz baz);
}

public class Foo : IFoo
{
    public void Bar(ref Baz baz)
    {
         var errorCode = NativeMethods.Bar(baz);
         if (errorCode != ErrorCode.None) throw new FooException(errorCode);
    }         
}

现在,我可以在代码中使用IFoo作为依赖项,并在测试中模拟它:

代码语言:javascript
复制
public class Component : IComponent
{
     public Component(IFoo foo, IService service) { ... }
}

这里好像出了点问题。NativeMethods必须是内部的,根据FxCop的说法。因此,IFoo (从NativeMethods中提取)也是内部的,这是有意义的。但是我不能仅仅把它变成内部的b/c,它是用在一个公共的ctor中(应该保持公共的)。因此:为了实现松散耦合,我必须更改组件的可见性,否则这将是内部的。你们觉得这个怎么样?

另一个问题:组件有方法public void DoSomehing(Bar bar),它使用在NativeMethods.cs中定义的Bar。我也得把这件事公之于众。这一点,或者创建一个新的Bar类来包装NativeMethods+Bar。如果我采用公共方式,那么NativeMethods也成为公共的,FxCop抱怨说“嵌套类型不应该是可见的”。如果我走包装方式..。嗯,我觉得为所有的“本地人”做这件事太费劲了。哦,还有第三种方法:将类型从NativeMethods中移开,并将它们公之于众。然后FxCop对它们进行分析,找出当它们嵌套在NativeMethods中时所隐藏的所有错误。我真的不知道这里最好的方法是什么..。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-11-17 07:42:35

在这里,公共抽象类可能是您的朋友,而不是接口。

这可以包括内部抽象方法(引用内部类型),这实际上使从程序集外部以正常方式进行子类变得不可能(但InternalsVisibleTo将允许您创建一个用于测试的伪方法)。

基本上,接口的设计并不像从组件方面设计的那样好。

这正是我在野田时间 for CalendarSystem中所做的--它的API使用内部类型,但我想让它成为一个接口或抽象类。我在博客帖子中写到了访问的奇怪之处,您可能会觉得这很有趣。

票数 3
EN

Stack Overflow用户

发布于 2015-09-26 01:27:29

INativeMethods**?**提取如何提取

我们将免费得到的不完整的清单:

  • 对TDD的完全支持
  • 您不需要运行应用程序来验证大多数情况。
  • 非常容易模拟和添加对不同环境的支持\OS
  • 分析性能,测量WinApi的调用计数

给我看看密码

接口与WinApi完全相同:

代码语言:javascript
复制
 internal interface INativeMethods    
 {
    IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wparam, StringBuilder lparam);

    bool GetWindowRect(IntPtr hwnd, out Rect rect);

    IntPtr GetWindow(IntPtr hwnd, uint cmd);

    bool IsWindowVisible(IntPtr hwnd);

    long GetTickCount64();

    int GetClassName(IntPtr hwnd, StringBuilder classNameBuffer, int maxCount);

    int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out Rect rect, int sizeOfRect);

    bool GetWindowPlacement(IntPtr hwnd, ref WindowPlacement pointerToWindowPlacement);

    int GetDeviceCaps(IntPtr hdc, int index);
}

实现是静态类的瘦代理:

代码语言:javascript
复制
internal class NativeMethodsWraper : INativeMethods
{       
    public IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wparam, StringBuilder lparam)
    {
        return NativeMethods.SendMessage(hwnd, msg, wparam, lparam);
    }

    public bool GetWindowRect(IntPtr hwnd, out Rect rect)
    {
        return NativeMethods.GetWindowRect(hwnd, out rect);
    }

    public IntPtr GetWindow(IntPtr hwnd, uint cmd)
    {
        return NativeMethods.GetWindow(hwnd, cmd);
    }

    public bool IsWindowVisible(IntPtr hwnd)
    {
        return NativeMethods.IsWindowVisible(hwnd);
    }

    public long GetTickCount64()
    {
        return NativeMethods.GetTickCount64();
    }

    public int GetClassName(IntPtr hwnd, StringBuilder classNameBuffer, int maxCount)
    {
        return NativeMethods.GetClassName(hwnd, classNameBuffer, maxCount);
    }

    public int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out Rect rect, int sizeOfRect)
    {
        return NativeMethods.DwmGetWindowAttribute(hwnd, attribute, out rect, sizeOfRect);
    }

    public bool GetWindowPlacement(IntPtr hwnd, ref WindowPlacement pointerToWindowPlacement)
    {
        return NativeMethods.GetWindowPlacement(hwnd, ref pointerToWindowPlacement);
    }

    public int GetDeviceCaps(IntPtr hdc, int index)
    {
        return NativeMethods.GetDeviceCaps(hdc, index);
    }
}

让我们用P\Invoke导入来完成这一点

代码语言:javascript
复制
internal static class NativeMethods
{
    [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
    public static extern int GetDeviceCaps(IntPtr hdc, int index);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsWindowVisible(IntPtr hWnd);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, [Out] StringBuilder lParam);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

    [DllImport("kernel32.dll")]
    public static extern long GetTickCount64();

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);

    [DllImport(@"dwmapi.dll")]
    public static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetWindowPlacement(IntPtr hWnd, ref WindowPlacement lpwndpl);
}

示例用法

代码语言:javascript
复制
internal class GetTickCount64TimeProvider : ITimeProvider
{
    private readonly INativeMethods _nativeMethods;

    public GetTickCount64TimeProvider(INativeMethods nativeMethods)
    {
        _nativeMethods = nativeMethods;
    }

    public Timestamp Now()
    {
        var gtc = _nativeMethods.GetTickCount64();

        var getTickCountStamp = Timestamp.FromMilliseconds(gtc);
        return getTickCountStamp;
    }
}

单元测试

很难相信,但是可以通过模拟WinApi来验证任何期望

代码语言:javascript
复制
[Test]
public void GetTickCount64_ShouldCall_NativeMethod()
{
    var nativeMock = MockRepository.GenerateMock<INativeMethods>();            
    var target = GetTarget(nativeMock);

    target.Now();

    nativeMock.AssertWasCalled(_ => _.GetTickCount64());
}



[Test]
public void Now_ShouldReturn_Microseconds()
{
    var expected = Timestamp.FromMicroseconds((long) int.MaxValue * 1000);
    var nativeStub = MockRepository.GenerateStub<INativeMethods>();
    nativeStub.Stub(_ => _.GetTickCount64()).Return(int.MaxValue);
    var target = GetTarget(nativeStub);

    var actual = target.Now();

    Assert.AreEqual(expected, actual);
}


private static GetTickCount64TimeProvider GetTarget(INativeMethods nativeMock)
{
    return new GetTickCount64TimeProvider(nativeMock);
}

模拟out\ref参数可能会引起头痛,因此下面是供将来参考的代码:

代码语言:javascript
复制
[Test]
public void When_WindowIsMaximized_PaddingBordersShouldBeExcludedFromArea()
{
    // Top, Left are -8 when window is maximized but should be 0,0
    // http://blogs.msdn.com/b/oldnewthing/archive/2012/03/26/10287385.aspx
    INativeMethods nativeMock = MockRepository.GenerateStub<INativeMethods>();

    var windowRectangle = new Rect() {Left = -8, Top = -8, Bottom = 1216, Right = 1936};
    var expectedScreenBounds = new Rect() {Left = 0, Top = 0, Bottom = 1200, Right = 1920};
    _displayInfo.Stub(_ => _.GetScreenBoundsFromWindow(windowRectangle.ToRectangle())).Return(expectedScreenBounds.ToRectangle());

    var hwnd = RandomNativeHandle();
    StubForMaximizedWindowState(nativeMock, hwnd);
    StubForDwmRectangle(nativeMock, hwnd, windowRectangle);
    WindowCoverageReader target = GetTarget(nativeMock);

    var window = target.GetWindowFromHandle(hwnd);


    Assert.AreEqual(WindowState.Maximized, window.WindowState);
    Assert.AreEqual(expectedScreenBounds.ToRectangle(), window.Area);
}

private void StubForDwmRectangle(INativeMethods nativeMock, IntPtr hwnd, Rect rectToReturnFromWinApi)
{
    var sizeOf = Marshal.SizeOf(rect);
    var rect = new Rect();

    nativeMock.Stub(_ =>
    {
        _.DwmGetWindowAttribute(
            hwnd, 
            (int)DwmWindowAttribute.DwmwaExtendedFrameBounds,
            out rect,  // called with zeroed object
            sizeOf);
    }).OutRef(rectToReturnFromWinApi).Return(0);
}

private IntPtr RandomNativeHandle()
{
    return new IntPtr(_random.Next());
}

private void StubForMaximizedWindowState(INativeMethods nativeMock, IntPtr hwnd)
{
    var maximizedFlag = 3;
    WindowPlacement pointerToWindowPlacement = new WindowPlacement() {ShowCmd = maximizedFlag};
    nativeMock.Stub(_ => { _.GetWindowPlacement(Arg<IntPtr>.Is.Equal(hwnd), ref Arg<WindowPlacement>.Ref(new Anything(), pointerToWindowPlacement).Dummy); }).Return(true);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8163575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档