2012-02-27 73 views
0

在运行时,我需要能够让我的加载的C++程序集在顶级应用程序中注册它们的版本信息。我正在考虑类似于:运行时的.NET程序集初始化

 array<System::Reflection::Assembly^>^ assemblies = System::AppDomain::CurrentDomain->GetAssemblies(); 

    for each(System::Reflection::Assembly^ assembly in assemblies) 
    {} 

但是,如何确定哪些是我的组件和哪些是系统组件。有什么方法可以为我的类添加一些静态方法,以便代码可以调用?

这是我实际使用的代码,我试图获取Foo类的属性,以便我可以调用静态方法来请求它注册自己。

public ref class Foo 
{ 
public: 

    Foo() 
    { 
    }; 

private: 

}; 

public ref class InitOnLoad : System::Attribute 
{ 
public: 

    InitOnLoad() 
    { 
    Foo ^foo = gcnew Foo(); 
    System::Type^ thisType = foo->GetType(); 

    // get a list of types which are marked with the InitOnLoad attribute 
    array<System::Reflection::Assembly^>^ assemblies = System::AppDomain::CurrentDomain->GetAssemblies(); 

    for each(System::Reflection::Assembly^ assembly in assemblies) 
    { 
     try 
     { 
      System::Type^ type = System::Type::GetType("UtilsDotNet.Foo"); 

      array<Object^>^ attributes = assembly->GetCustomAttributes(type, false); 

      if(attributes->Length > 0) 
      { 
       auto field = 
       type->GetFields(
       System::Reflection::BindingFlags::Static | 
       System::Reflection::BindingFlags::Public | 
       System::Reflection::BindingFlags::NonPublic); 
      } 

     } 
     catch (...) 
     { 
     } 
    } 
    } 
}; 

回答

1

我会为您的程序集添加一个自定义属性。在使用版本号注册向前移动之前,您可以测试每个程序集的属性。

我的语法可能是错误的,但是......

System::Type^ type = System::Type::GetType("UtilsDotNet.Foo"); 
array<Object^>^ attributes = assembly->GetCustomAttributes(type, false); 

应该

array<Object^>^ attributes = assembly->GetCustomAttributes(__typeof(InitOnLoad), false); 

我不知道C++的标记与属性的组合方式,但C#方式将该行放在Assembly.cs文件(在属性文件夹下)

[assembly: InitOnLoad()] 

此外,你不应该有用于枚举属性构造函数中的程序集的代码。如果你这样做,每当发现这些属性中的任何一个时,都会运行此代码。我将这些代码放在一个单独的方法中,也许是属性的静态方法。

最后,请记住,如果您使用的是后期装配,您还需要听取AssemblyLoad事件。

+0

感谢您的回复。我试图做类似于你提到的,但是当我由于某种原因调用GetCustomAttributes时,它有0个属性。 – user1145533 2012-02-27 16:28:32

+0

发布您的属性代码和您的代码寻找属性,我会尽力帮助你。 – 2012-02-27 17:01:39

+0

我刚刚更新了我正在尝试的代码,当它加载时,我无法让GetCustomAttributes返回任何内容。我已经尝试__typeof获取类型时,但也没有工作。 – user1145533 2012-02-27 17:29:33