简体   繁体   中英

Extract arguments of method calls with Mono.Cecil

I am trying to extract all arguments passed to a specific method with Mono.Cecil.
In a post-processing script that runs right after the project being build, I am able to find all method calls, and even extract the type of the argument passed to the function. However, I am not able to get the actual value... So is this even possible with Mono.Cecil, and if yes, what value do I need to look at?

Here is my current code :

List<MethodDefinition> methods = new List<MethodDefinition> ();
foreach (ModuleDefinition _module in assembly.Modules) {
    foreach (TypeDefinition _type in _module.Types) {
        methods.AddRange (_type.Methods);
    }
}
var uiExtensionMethod = methods
      .Where(m => m.DeclaringType.Name == "SetCustomText").FirstOrDefault();
var instructions = uiExtensionMethod.Body.Instructions;
var count = instructions.Count;
var instructionArray = instructions.ToArray();
for (int i = 0; i < count; i++) {
    if (instructionArray [i] != null) {
        if (instructionArray [i].Operand != null) {
            var paramType = instructionArray [i].Operand.ToString ();
            // So here I have the type of the parameter, but I cannot get the value...
        }
    }
}

Okay, so I found the solution to this.

The problem was, that Mono.Cecil did indeed find my method calls, but it processed them inside the file, where the argument was already written into a variable, and therefor unable to be converted to a string.

So my solution is, parsing ALL methods that have a string as an Operand, and then detecting their NEXT operation. If the next operation is my function of choice, THEN I found the string I am looking for :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM