2013-12-22 195 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