一些有用的链接
2014-10-08 21:45
232 查看
Nsis
http://blog.csdn.net/xiliang_pan/article/details/7106684
http://blog.csdn.net/dyllove98/article/details/8762519
http://www.flighty.cn/html/bushu/
插件
http://blog.csdn.net/absurd/article/details/877063
http://blog.csdn.net/yuvmen/article/details/5879371
http://blog.csdn.net/renzeGIS/article/details/9351877
SVN
http://blog.csdn.net/zs8861/article/details/7879594
编写、加载和存取插件程序(Plug-Ins)
Nsis
http://blog.csdn.net/xiliang_pan/article/details/7106684
http://blog.csdn.net/dyllove98/article/details/8762519
http://www.flighty.cn/html/bushu/
插件
http://blog.csdn.net/absurd/article/details/877063
http://blog.csdn.net/yuvmen/article/details/5879371
http://blog.csdn.net/renzeGIS/article/details/9351877
SVN
http://blog.csdn.net/zs8861/article/details/7879594
编写、加载和存取插件程序(Plug-Ins)
在 2005 年一月刊的 MSDN 杂志文章中,你有一个例子程序的代码是用混合模式编写的。有没有可能动态加载 .NET 类或 DLL 并调用那些函数呢?假设我有一个本机 C++ 应用程序,我想允许用户在 .NET 中为该 C++ 程序编写插件。就像在 .NET 中使用 LoadLibrary 加载 DLLs 一样。 Ravi Singh 我正在用 Visual C++ 6.0 编写一个插件应用,它是一个 DLL,输出和接收纯虚拟接口指针。加载 DLL 后,EXE 便调用 DLL 中输出的 C 函数,该函数返回一个纯虚拟接口指针。然后 EXE 调用该接口上的方法,有时会传回另一个接口指针给 DLL 处理。 目前有人要求必须用 C#,Visual Basic .NET 和其它语言编写插件。我没有什么基于 .NET 的编程经验,不懂托管和非托管代码之间的通讯问题,我找到许多有关这方面的信息,但是越看越糊涂。我如何才能让用户编写基于.NET 语言的插件? Daniel Godson 在 MSDN 杂志 2003 年 10 月刊中,有一篇 Jason Clark 写的一篇关于插件的文章,但我并不介意在此复习一下这个主题,尤其是因为插件本身就是 .NET 框架中举足轻重的部分(参见:Plug-Ins: Let Users Add Functionality to Your .NET Applications with Macros and Plug-Ins)。毕竟,微软 .NET 框架的主要目的之一就是为编写可重用的软件组件提供一种语言无关的系统。从第一个 “Hello,world”程序到现在,这已经成为软件 开发至高无上的准则。可重用性从拷贝/粘贴到子例程,再到静态链接库,再到 DLLs 以及更专业的 VBX,OCX 和 COM。虽然最后三个东西属于不同的主题(它们都是 本机 DLLs),.NET 框架标志着一个真正的开端,因为所有代码都被编译成微软中间语言(MSIL)。互用性成为一种不可或缺的成分,因为在公共语言运行时层面,所有代码都一样。这就使得编写支持语言中立的插件体系结构 的程序变得尤其容易。 那么在你的 C++ 程序中如何利用这个优势呢?Daniel 的虚拟函数指针系统就是一个手工自制的 COM。它就是 COM 对象本质之所在:纯虚拟函数指针。你可以为插件模型使用 COM ,开发人员可以用任何面向 .NET 的语言编写插件,因为这个框架让你创建和使用 COM 对象。但众所周知, COM 编码非常繁杂,因为它需要考虑的细节颇多,例如注册、引用计数,类型库等等――这些东西足以使你认为 COM 简直就是“Cumbersome Object Model”(麻烦对象模型)。如果你正在编写新代码并试图简化你的日常工作,那么就用 .NET 直接实现一个插件模型吧,我现在就是在讨论这个话题。 首先让我回答 Ray 的问题,即:在 .NET 中有没有类似 LoadLibrary 的东西,答案是:有,你可以用静态方法 System::Assembly::Load 加载任何框架程序集(就是一个包含 .NET 类的 DLL)。此外,.NET 支持反射机制。每个程序集都提供所有你需要的信息,如:该程序集有什么类,什么方法以及何种接口。不需要关心 GUIDs,注册,引用计数等诸如此类的事 情。 在我展示更一般的插件系统之前,我将从一个简单的例子开始,Figure 1 是一个 C# 类,它提供一个静态函数 SayHello。注意与 C/C++ 不同,在 .NET 中函数不单独输出;每个函数必须属于某个类,虽然这个类可以为静态的,也就是说它不需要实例化。为了将 MyLib.cs 编译成一个库,可以这样做: view source print? 01. Figure 1 MyLib.cs 02. 03. using System; 04. using System.Reflection; 05. using System.Runtime.CompilerServices; 06. 07. namespace MyLib 08. { 09. // Class that exports a single static function 10. public class MyClass 11. { 12. public MyClass(){} 13. 14. static public void SayHello(String who) 15. { 16. Console.WriteLine( "Hello, world, from {0}" , who); 17. } 18. } 19. } view source print? 1. csc /target:library MyLib.cs 编译器将产生一个名为 MyLib.dll 的 .NET 程序集。为了通过托管扩展从 C++ 中调用 SayHello,你得这样写: view source print? 1. #using < mscorlib.dll > 2. #using < MyLib.dll > 3. using namespace MyLib; 4. void main () 5. { 6. MyClass::SayHello( "test1" ); 7. } 编译器链接到 MyLib.dll 并调用正确的入口点。这一切都简单明了,它属于 .NET 的基础。现在假设你不想在编译时链接 MyLib,而是想进行动态链接,就像在 C/C++ 用 LoadLibrary 那样。毕竟,插件无非是要在运行时链接,在你已经生成并交付的应用程序之后。Figure 2 所做的事情和前述代码段一样,只不过它是动态加载 MyLib 的。关键函数是 Assembly::Load。一旦你加载了该程序集,你便可以调用 Assembly::GetType 来获得有关类的 Type 信息(注意你必须提供全限定名字空间和类名),进而调用 Type::GetMethod 来获取有关方法的信息,甚至是调用它,就像这样: view source print? 01. Figure 2 Loading MyLib Dynamically 02. 03. using < mscorlib.dll > 04. #using < System.dll > 05. #include < vcclr.h > 06. #include < stdio.h > 07. #include < tchar.h > 08. 09. using namespace System; 10. using namespace System::Reflection; 11. 12. void main () 13. { 14. try { 15. // Load library dynamically: 16. Assembly* a = Assembly::Load( "MyLib" ); 17. if (a) { 18. Console::WriteLine( "Assembly = {0}" , a); 19. Type* t = a->GetType( "MyLib.MyClass" ); 20. if (t) { 21. Console::WriteLine( "Type = {0}" , t); 22. MethodInfo* m = t->GetMethod( "SayHello" ); 23. if (m) { 24. Console::WriteLine( "Method = {0}\n" , m); 25. String* args[] = { "Test2" }; 26. m->Invoke(NULL, args); 27. } else { 28. printf ( "Can't find SayHello!\n" ); 29. } 30. } else { 31. printf ( "Can't find MyLib.MyClass!\n" ); 32. } 33. } else { 34. printf ( "Can't load MyLib!\n" ); 35. } 36. } catch (Exception* e) { 37. Console::WriteLine( "*** Oops: Exception occurred: {0}" , e); 38. } 39. } view source print? 1. MethodInfo* m = ...; // get it 2. String* args[] = { "Test2" }; 3. m->Invoke(NULL, args); 第一个参数是对象实例(此例中为 NULL,因为 SayHello 是静态的),第二个参数是 Object (对象)数组,明白了吗? 在继续往下讨论之前,我必须指出 Load 函数有几个,正是这一点很容易把我们搞糊涂。.NET 被设计用来解决的一个问题就是所谓的 DLL 地狱(DLL Hell)问题,当几个应用程序共享某个共公 DLL 并想要更新该 DLL 时常常会发生这个问题――它能使某些应用程序崩溃。而在 .NET 中,不同的应用程序可以加载同一个程序集/DLL的不同版本。不幸的是,DLL 地狱现在变成了 Load 地狱(Load Hell),因为加载程序集的规则是如此复杂,我都可以专门写一个专栏来描述它。 加载并将程序集邦定到你的程序的过程称为熔接(fusion),甚至框架带有专门的程序,fuslogyw.exe (Fusion Log Viewer)来做这件事情,你可以用它确定加载了那个程序集的哪个版本。正像我说过的,要完整地描述框架是如何加载并邦定程序集,以及它是如何定义“身份”(identity)的需要几页篇幅 才能说清楚。但对于插件来说,只需考虑两个函数:Assembly::Load 和 Assembly::LoadFrom。 Assembly::Load 的参数可以是完整的或部分的名称(例如,“MyLib”或者“MyLib Version=xxx”Culture=xxx”)。Figure 2 中的测试程序加载“MyLib”,然后显示完整的程序集名称,如 Figure 3 所示: Figure 3 测试程序 Assembly::Load 使用框架的发现规则来决定实际加载了哪个文件。它在 GAC(全局程序集缓冲:Global Assembly Cache)里,你的程序给出的路径以及应用程序所在的目录以及诸如此类的路径中查找。 另一个函数 Assembly::LoadFrom 使你能从外部路径加载程序集。这里有一点模糊的是如果相同的程序集(由同一性规则确定)已经被从不同的路径加载,框架将会使用之。所以 LoadFrom 并不总是正确地使用通过该路径指定的程序集,尽管大多数时候能正确使用。晕了吧?还有另外一个方法是 Assembly::LoadFile,它总是加载请求的路径――但你几乎从来用不上 LoadFile,因为它解决不了依赖性问题,并且无法将程序集加载到正确的环境中(LoadFrom)。不用去了解所有的细节,我将对 LoadFrom 进行简单地讨论,以此说明对于简单的插件模型,它是一个很好用的函数。 这样一个模型的基本思路是定义一个接口,然后让其他人编写实现此接口的类。你的应用程序可以调用 Assembly::LoadFrom 来加载插件,并用反射来查找实现你所定义之接口的类。不过在你动手之前,有两个重要的问题要问:你的应用程序需要在运行中卸载或重新加载插件吗?你的程序需要 考虑对插件必须使用的文件或其它资源进行安全存取吗?如果你对两个问题的答案都为 YES,那么你将需要 AppDomain。 在框架中,没有办法直接卸载某个程序集。唯一途径是将程序集加载到单独的 AppDomain,然后卸载整个 AppDomain。每个 AppDomain 还可以有其自己的安全许可。 AppDomains 带有一个隔离的处理单元,通常由单独的进程操控,一般都用于服务器程序中,服务器基本上都是昼夜运行(24x7),并需要动态加载和卸载组件而不用重新启动。AppDomains 还被用于限制插件获得的许可,以便某个应用能加载非信任组件而不用担心其恶意行为。为了启用这种隔离,需要远程机制来使用多个 AppDomains;不同 的 AppDomains 其对象无法相互直接调用,他们必须跨 AppDomain 边界进行封送。尤其是类的共享实例必须从 MarshalByRefObject 派生。 这就是我现在要讲的 AppDomains。接下来我将描述一个非常简单的插件模型,它不需要 AppDomains。假设你生成了一个图像编辑器,并且你想让其他开发人员编写插件来实现诸如曝光、模糊或使部分像素变绿等特效。 此外,如果你拥有数据库所有权,你想让别的开发人员编写专门的导入/导出过滤器,以便对你的数据和他们自定义的文件格式之间进行转换。在这种情况下,应用程序在启动时加载所有的插件,插件一直保留加载状态,也就是说一直到用户退出程序。该模型不需要服务器程序具备重新加载功能,插件与应用程序本身具有相同的安全许可。所以没有必要使用 AppDomains;所有插件可被加载到主应用程序域中。这是桌面应用程序典型的使用模式。 为了真正实现这个模型,首先要定义每个插件必须实现的接口。接口实际上就像是 COM 的接口,它是一个抽象基类,在这个类中定义了插件必须实现的属性和方法。在本文的例子中,我顺便写了一个可扩展的文本编辑器,名叫 PGEdit,它带有一个插件接口 ITextPlugin(参见 Figure 4)。ITextPlugin 有两个属性,MenuName 和 MenuPrompt, 以及一个方法 Transform,该方法带一个串参数,对传入的字符串进行处理,然后返回新的串。我为 PGEdit 实现了三个具体的插件:PluginCaps,PluginLower 和 PluginScramble,其功能分别是大写,小写和打乱文本字符。如 Figure 5 所示,PGEdit 的三个插件被添加到 Edit 菜单的情形。 view source print? 01. Figure 4 ITextPlugin 02. 03. 04. #pragma once 05. 06. using namespace System; 07. using namespace System::ComponentModel; 08. 09. namespace TextPlugin { 10. 11. // plug-in interface definition 12. public __gc __interface ITextPlugin 13. { 14. [ReadOnly( true )] 15. __property String* get_MenuName(); 16. 17. [ReadOnly( true )] 18. __property String* get_MenuPrompt(); 19. 20. String* Transform(String* text); 21. }; 22. } Figure 5 带有三个插件的 PGEdit 我编写了一个类叫 CPluginMgr,它负责管理插件(参见 Figure 6)。PGEdit 启动时调用 CPluginMgr::LoadAll 加载所有插件: view source print? 001. Figure 6 PluginMgr 002. 003. PluginMgr.h 004. #pragma once 005. #include < vector > 006. 007. using namespace std; 008. using namespace System; 009. using namespace System::Collections; 010. 011. // STL vector of managed Objects, wrapped as gcroot handle 012. typedef vector < gcroot< Object*> > PLUGINLIST; 013. 014. //////////////// 015. // .NET Plug-in Manager. This class will load all the DLLs in a folder, 016. // looking for assemblies that contain classes that implement a specific 017. // interface, and will instantiate any such classes it finds, adding them 018. // to a list (STL vector). Note this is a native class, which is why I 019. // have to use gcroot, because a native class can't hold pointers to 020. // managed objects. 021. // 022. class CPluginMgr { 023. public : 024. CPluginMgr( LPCTSTR dir=NULL); 025. virtual ~CPluginMgr(); 026. 027. PLUGINLIST m_objects; // list (vector) of plug-in objects 028. 029. // load all DLLs that implement given interface. 030. int LoadAll(Type* iface, int nReserve=10); 031. 032. // Get ith plug-in 033. Object* CPluginMgr::GetPlugin( int i) 034. { 035. return m_objects[i]; 036. } 037. 038. // ditto, using [] 039. Object* operator[]( int i) 040. { 041. return GetPlugin(i); 042. } 043. 044. protected : 045. // helper: load single plug-in 046. int LoadPlugin(Type* iface, LPCTSTR pathname); 047. 048. CString m_dir; // plug-in directory where DLLs are 049. }; 050. 051. PluginMgr.cpp 052. #include "stdafx.h" 053. #include "PluginMgr.h" 054. 055. using namespace System; 056. using namespace System::Reflection; 057. 058. CPluginMgr::CPluginMgr( LPCTSTR dir) : m_dir(dir) 059. { 060. if (m_dir.IsEmpty()) { 061. // default plug-in directory is exedir/PlugIns, where exedir is the 062. // folder containing the executable 063. LPTSTR buf = m_dir.GetBuffer(MAX_PATH); // buffer in which to copy 064. GetModuleFileName(NULL, buf, MAX_PATH); // exe path 065. PathRemoveFileSpec(buf); // remove file name part 066. m_dir.ReleaseBuffer(); // free buffer 067. m_dir += _T( "\\PlugIns" ); // append "PlugIns" 068. } 069. } 070. 071. CPluginMgr::~CPluginMgr() 072. { 073. } 074. 075. ////////////////// 076. // Load and instantiate all plug-ins that implement a given interface. Note 077. // this will load all DLLs in the plug-in directory, even ones that don't 078. // implement the interface—there's no way to unload an Assembly w/o using 079. // AppDomains. 080. // 081. int CPluginMgr::LoadAll(Type* iface, int nReserve) 082. { 083. ASSERT(iface); 084. ASSERT(iface->IsInterface); 085. 086. m_objects.reserve(nReserve); // for efficiency 087. 088. // Use MFC to find *.dll in the plug-ins directory, and load each one 089. CFileFind libs; 090. CString spec; 091. spec.Format(_T( "%s\\*.dll" ), m_dir); 092. TRACE(_T( "Loading %s\n" ), spec); 093. BOOL bMore = libs.FindFile(spec); 094. while (bMore) { 095. bMore = libs.FindNextFile(); 096. LoadPlugin(iface, libs.GetFilePath()); 097. } 098. TRACE(_T( "%d plugins found\n" ), m_objects.size()); 099. return m_objects.size(); 100. } 101. 102. ////////////////// 103. // Load single DLL file, looking for given interface 104. // 105. int CPluginMgr::LoadPlugin(Type* iface, LPCTSTR pathname) 106. { 107. int count=0; 108. try { 109. Assembly * a = Assembly::LoadFrom(pathname); 110. Type* types[] = a->GetTypes(); 111. for ( int i=0; iLength; i++) { 112. Type *type = types[i]; 113. if (iface->IsAssignableFrom(type)) { 114. TRACE(_T( "Found type %s in %s\n" ), CString(type->Name), 115. pathname); 116. Object* obj = Activator::CreateInstance(type); 117. m_objects.push_back(obj); 118. count++; 119. } 120. } 121. 122. } catch (Exception* e) { 123. TRACE(_T( "*** Exception %s loading %s, ignoring\n" ), 124. CString(e->ToString()), pathname); 125. } 126. if (!count) 127. TRACE(_T( "*** Didn't find %s in %s\n" ), CString(iface->Name), 128. pathname); 129. 130. return count; 131. } view source print? 1. BOOL CMyApp::InitInstance() 2. { 3. ... 4. m_plugins.LoadAll(__typeof(ITextPlugin)); 5. } 此处 m_plug-ins 为 CPluginMgr 的一个实例。构造函数的参数为一个子目录名(默认值是 “Plugins”);LoadAll 搜索该文件夹查找程序集,在该程序集中包含的类实现了所请求的接口。当它找到这样一个程序集,CPluginMgr 便创建一个该类的实例并将它添加到一个列表中(STL vector)。下面是关键代码段: view source print? 1. for ( /* each type in assembly*/ ) { 2. if (iface->IsAssignableFrom(type)) { 3. {Object* obj = Activator::CreateInstance(type); 4. m_objects.push_back(obj); 5. count++; 6. } 7. } 换句话说,如果类型(type)可被赋值给 ITextPlugin,CPluginMgr 则创建一个实例并将其添加到数组。因为 CPluginMgr 是一个本机类,它无法直接保存托管对象,所以数组 m_objects 实际上是一个 gcroot 类型的数组。如果你在 Visual C++ 2005 中使用新的 C++ 语法,可用 Object^ 替代。注意 CPluginMgr 是一个通用类,支持任何你设计的接口。只要实例化并调用 LoadAll 即可,并且你最终要用插件对象数组。CPluginMgr 报告它在 TRACE 流中找到的插件。如果你有多个接口,那么你可能得为每个接口使用单独的 CPluginMgr 实例,以便保持插件之间的隔离。 在性能上,CLR 团队的 Joel Pobar 在 MSDN 杂志 2005 年7月刊里写了一篇令人恐怖的文章(Reflection: Dodge Common Performance Pitfalls to Craft Speedy Applications),在这篇文章中,他讨论了使用反射的最佳实践。他建议利用程序集层面的属性来具体说明程序集中哪个类型实现了插件接口。这样便允许插件管理器快速查找并实例化插件,而不是非得循环查找程序集中的每种类型,如果类型太多,那将是个昂贵的操作。如果你发现本期专栏里的代码在加载你自己的插件时性能很糟的话,你应该考虑改用 Joel 推荐的方法。但是对于一般的情况,这个代码足以胜任。 一旦你加载了插件,那么如何使用它们呢?这样依赖于你的应用程序,一般你会有一些像下面这样的典型代码: view source print? 1. PLUGINLIST& pl = theApp.m_plugins.m_objects; 2. for (PLUGINLIST::iterator it = pl.begin(); it!=pl.end(); it++) { 3. Object* obj = *it; 4. ITextPlugin* plugin = dynamic_cast < ITEXTPLUGIN* >(obj); 5. plugin->DoSomething(); 6. } 7. } (PLUGINLIST 是一个 typedef,用于 vector< GCROOT< OBJECT*>>)。PGEdit 的 CMainFrame::OnCreate 函数有一个类似这样的循环,添加每个插件的 MenuName 到 PGEdit 的 Edit 菜单。CMainFrame 指定命令 IDs 从 IDC_PLUGIN_BASE 开始。Figure 7 示范了视图是如何使用 ON_COMMAND_RANGE 来处理命令的。具体细节请下载源代码。 view source print? 01. Figure 7 Using ON_COMMAND_RANGE 02. 03. #include "StdAfx.h" 04. #include "View.h" 05. #include "PGEdit.h" 06. 07. #using < TextPlugin.dll > 08. using namespace TextPlugin; 09. 10. IMPLEMENT_DYNCREATE(CMyView, CEditView) 11. BEGIN_MESSAGE_MAP(CMyView, CEditView) 12. ON_COMMAND_RANGE(IDC_PLUGIN_BASE, IDC_PLUGIN_END, OnPluginCmd) 13. ON_UPDATE_COMMAND_UI_RANGE(IDC_PLUGIN_BASE, IDC_PLUGIN_END, 14. OnPluginCmdUI) 15. END_MESSAGE_MAP() 16. 17. void CMyView::OnPluginCmd( UINT id) 18. { 19. CEdit& edit = GetEditCtrl(); 20. int begin,end; 21. edit.GetSel(begin,end); 22. if (end>begin) { 23. Object* obj = theApp.m_plugins.GetPlugin(id - IDC_PLUGIN_BASE); 24. ASSERT(obj); 25. ITextPlugin* plugin = dynamic_cast < ITextPlugin* >(obj); 26. if (plugin) { 27. CString text; 28. edit.GetWindowText(text); 29. text = text.Mid(begin, end-begin); 30. text = plugin->Transform(text); 31. edit.ReplaceSel(text); 32. edit.SetSel(begin,end); 33. } 34. } 35. } view source print? 1. void CMyView::OnPluginCmdUI(CCmdUI* pCmdUI) 2. { 3. CEdit& edit = GetEditCtrl(); 4. int begin,end; 5. edit.GetSel(begin,end); 6. pCmdUI->Enable(begin!=end); 7. } 我已展示了 PGEdit 是如何加载和存取插件的,但你要如何实现插件呢?那是很容易的事情。首先生成一个定义接口的程序集——本文的例子中就是 TextPlugin.dll。该程序集不实现任何代码或类,仅仅定义接口。记住,.NET 是语言中立的,所以没有源代码,与 C++ 头文件完全不同。相反,你生成定义接口的程序集并将它分发给编写插件的开发人员。插件与该程序集链接,于是他们从你提供的接口派生。例如,下面的 C# 代码: view source print? 1. using TextPlugin; 2. public class MyPlugin : ITextPlugin 3. { 4. ... // implement ITextPlugin 5. } Figure 8 展示了用 C# 编写的 PluginCaps 插件。正像你所看到的,它十分简单。有关细节请参考本文的源代码。 view source print? 01. Figure 8 CapsPlugin 02. 03. using System; 04. using System.Reflection; 05. using System.Runtime.CompilerServices; 06. using TextPlugin; 07. 08. public class CapsPlugin : ITextPlugin 09. { 10. public CapsPlugin() {} 11. 12. public String MenuName 13. { 14. get { return "Uppercase" ; } 15. } 16. 17. public String MenuPrompt 18. { 19. get { return "Convert selected text to ALL UPPERCASE" ; } 20. } 21. 22. public String Transform(String text) 23. { 24. return text.ToUpper(); 25. } 26. } 顺祝编程愉快! 您的提问和评论可发送到 Paul 的信箱:cppqa@microsoft.com. |
作者简介 Paul DiLascia 是一名自由作家,软件咨询顾问以及大型 Web/UI 的设计师。他是《Writing Reusable Windows Code in C++》书(Addison-Wesley, 1992)的作者。业余时间他开发 PixeLib,这是一个 MFC 类库,从 Paul 的网站 http://www.dilascia.com 可以获得这个类库。 |