Best practices for organizing .NET P/Invoke code to Win32 APIs
- by Paul Sasik
I am refactoring a large and complicated code base in .NET that makes heavy use of P/Invoke to Win32 APIs. The structure of the project is not the greatest and I am finding DllImport statements all over the place, very often duplicated for the same function, and also declared in a variety of ways:
The import directives and methods are sometimes declared as public, sometimes private, sometimes as static and sometimes as instance methods. My worry is that refactoring may have unintended consequences but this might be unavoidable.
Are there documented best practices I can follow that can help me out?
My instict is to organize a static/shared Win32 P/Invoke API class that lists all of these methods and associated constants in one file...
(The code base is made up of over 20 projects with a lot of windows message passing and cross-thread calls. It's also a VB.NET project upgraded from VB6 if that makes a difference.)