Question

I need to use a native DLL from C#. The DLL exposes several methods which I can access via P/Invoke, and several types. All this code is in a standard NativeMethods class. To keep things simple it looks like this:

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;
    }
}

To achieve loose coupling I need to extract an interface and implement it using calls to NativeMethods:

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);
    }         
}

Now I can just use IFoo as a dependency in my code and mock it in tests:

public class Component : IComponent
{
     public Component(IFoo foo, IService service) { ... }
}

Something seems wrong here. NativeMethods must be internal according to FxCop. It makes sense then for IFoo (which was extracted from NativeMethods) to be internal too. But I can't just make it internal b/c it is used in a public ctor (which should stay public). So: in order to achieve loose coupling I have to change the visibility of a component which otherwise would have been internal. What do you guys think about this?

Another problem: Component has method public void DoSomehing(Bar bar) which uses the Bar defined in NativeMethods.cs. I have to make that public too for this to work. This, or make a new Bar class which wraps NativeMethods+Bar. If I go the public way then NativeMethods becomes public too and FxCop complains that "Nested types should not be visible". If I go the wrapper way... well, I feel it's too much of an effort to do it for all the "native types". Oh, there is the 3rd way: move the types away from NativeMethods and make them public. Then FxCop gets to analyze them and finds all the errors which were otherwise hidden when they were nested in NativeMethods. I really don't know what's the best way here...

Was it helpful?

Solution

It's possible that a public abstract class is your friend here, instead of an interface.

That can include internal abstract methods (referring to internal types), which actually makes it impossible to subclass in the normal way from outside the assembly (but InternalsVisibleTo will let you create a fake for testing).

Basically interfaces haven't really been designed as well as they could have been from a component aspect.

This is exactly what I did in Noda Time for CalendarSystem - its API uses internal types, but I wanted to make it an interface or abstract class. I wrote about the oddities of access in a blog post which you may find interesting.

OTHER TIPS

How about extracting INativeMethods?

Incomplete list of what we will get for free:

  • Complete support for TDD
  • You do not need to run your application to verify most of cases
  • Really easy to simulate and add support for different environments\OS
  • Profiling performance, measure call count to WinApi

Show me the code

Interface is identical to WinApi:

 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);
}

Implementation is a thin proxy to static class:

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);
    }
}

Let's complete this with P\Invoke imports

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);
}

Example usage

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;
    }
}

Unit testing

Hard to believe, but it possible to verify any expectation by mocking WinApi

[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);
}

Mocking out\ref params might cause headache so here is the code for future reference:

[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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top