Nested class with pinvoke in generic class

No idea why this limitation exists, but apparently it is not possible to call pinvoke methods in a nested class from a method in a generic class.

 I had something like this:

public class Foo
{
    private class FooGeneric
    {
        private HandleRef handle;
        private const uint SOMEMSG;

        private void DoSomething()
        {
            NativeMethods.SendMessage(handle, SOMEMSG, IntPtr.Zero, IntPtr.Zero);
        }
        
        private static class NativeMethods
        {
            [DllImport(“user32.dll”, CharSet = CharSet.Auto)]
            public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        }      
    }
}

Just before DoSomething was called in my code I got a TypeLoadException with the message:

Generic method or method in generic class is internal call, PInvoke, or is defined in a COM Import class.

Solved it by moving the NativeMethods class outside of the generic class.

Leave a Reply

Your email address will not be published.