将.NET P/Invoke代码组织到Win32 API的最佳实践 [英] Best practices for organizing .NET P/Invoke code to Win32 APIs

查看:72
本文介绍了将.NET P/Invoke代码组织到Win32 API的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构.NET中庞大而复杂的代码库,该代码库大量使用了对Win32 API的P/Invoke.该项目的结构并不是最好的结构,我到处都在发现DllImport语句,该语句经常为同一功能重复,并且还以多种方式声明:

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:

有时将import指令和方法声明为public,有时为private,有时声明为static,有时声明为实例方法.我担心的是重构可能会带来意想不到的后果,但这可能是不可避免的.

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?

我的目的是组织一个静态/共享的Win32 P/Invoke API类,该类在一个文件中列出所有这些方法和关联的常量... 编辑有多达70多个导入到user32 DLL中

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... EDIT There are over 70 imports to the user32 DLL.

(代码库由20多个项目组成,这些项目具有许多Windows消息传递和跨线程调用.如果有不同,它也是从VB6升级的VB.NET项目.)

(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.)

推荐答案

您可能会考虑在.NET框架中完成此操作的方式.它始终声明一个名为NativeMethods的静态类(在VB.NET中为Module),其中包含P/Invoke声明.您可能比Microsoft程序员更有条理,有很多重复的声明.不同的团队在框架的不同部分工作.

You might consider the way it was done in the .NET framework. It invariably declares a static class (Module in VB.NET) named NativeMethods that contains the P/Invoke declarations. You could be more organized than the Microsoft programmers, there are many duplicate declarations. Different teams working on different parts of the framework.

但是,如果要在所有项目之间共享,则必须将这些声明声明为Public而不是Friend.这不是很好,它应该是一个实现细节.我认为您可以通过在每个需要它的项目中重新使用源代码文件来解决此问题.我认为通常是忌讳的,但在这种情况下还可以.

However, if you want to share this among all projects you have to declare these declarations Public instead of Friend. Which isn't great, it ought to be an implementation detail. I think you can solve that by re-using the source code file in every project that needs it. Normally taboo but okay in this case, I think.

我亲自在需要它们的源代码文件中根据需要声明了它们,使它们成为私有".尤其是对于SendMessage而言,这在讨论参数类型时也确实有帮助.

I personally declare them as needed in the source code file that needs them, making them Private. That also really helps when lying about the argument types, especially for SendMessage.

这篇关于将.NET P/Invoke代码组织到Win32 API的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆