2012-02-27 25 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