2013-12-22 190 views
13

我一直有與我的項目靜態構造函數的一些問題。我需要爲類型「」添加一個靜態構造函數來調用我的資源解密方法。靜態構造函數的創建[Mono.Cecil]

在gif下面你會看到我碰到的問題。

我還將包含代碼片段。 enter image description here

代碼創建cctor:

MethodDefinition method = new MethodDefinition(
    ".cctor", 
    Mono.Cecil.MethodAttributes.Private 
    | Mono.Cecil.MethodAttributes.Static 
    | Mono.Cecil.MethodAttributes.HideBySig 
    | Mono.Cecil.MethodAttributes.SpecialName 
    | Mono.Cecil.MethodAttributes.RTSpecialName, 
    mod.Import(typeof(void)) 
); 

我也試圖改變屬性完全相同的矢野的。它以某種方式從未工作。 「作品」我的意思是檢測它作爲DotNet Resolver中的靜態構造函數。

下面是關於實際結果和預期結果的更多信息。

enter image description here

我沒有連接到我的入口點的ResolveEventHandler。我將它附加到正在被模糊處理的應用程序中,它位於「」類型的靜態構造函數中,即使在調用入口點之前也會執行該構造函數。

應用程序資源已使用AES進行加密,並且不會被dotnet解析器或其他反編譯器識別爲有效資源。我只是問爲什麼事件沒有被觸發,因爲當資源無效或缺失時應該觸發事件。正如你在示例中看到的,在應用程序啓動之前應該彈出一個消息框,但它永遠不會(字符串加密對字符串進行加密,因此有點難以看到字符串)。

任何幫助表示讚賞。

回答

5

使用本:

void AddConstructor(TypeDefinition type, MethodReference baseEmptyConstructor) 
{ 
    var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; 
    var method = new MethodDefinition(".ctor", methodAttributes, ModuleDefinition.TypeSystem.Void); 
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); 
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseEmptyConstructor)); 
    method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); 
    type.Methods.Add(method); 
} 

你也可以參考:

http://www.mono-project.com/Cecil:FAQ

+0

注:更換'MethodAttributes.Public'爲'MethodAttributes.Static'和'.ctor'爲'.cctor '如果你需要一個靜態構造函數 – Serg046