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.

14 thoughts on “Nested class with pinvoke in generic class

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

Leave a Reply

Your email address will not be published. Required fields are marked *