开发者

Make a call graph at run-time for a specific method

Say you have two simple interfaces and their methods:


ISerializable.Serialize(IValueWriter writer)
IValueWriter.WriteInt32(Int32 value)
IValueWRiter.WriteInt64(Int64 value)

When a class implements ISerializable I would like to be able to know which calls are made to the IValueWriter inside the ISerializable.Serialize(IValueWriter writer) implementation and generate a call graph from that. All of this needs to be done at run-time using reflect开发者_如何学Pythonion and without calling the Serialize method and it will be done also on classes which I have no control over as far as the code inside them goes.

Example:


public sealed class SomeObject : ISerializable
{
    private readonly Int32 first;
    private readonly Int64 second;

    public SomeObject(Int32 first, Int64 second)
    {
        this.first = first;
        this.second = second;
    }

    public void Serialize(IValueWriter writer)
    {
        writer.WriteInt32(this.first);
        writer.WriteInt64(this.second);
    }
}

The call graph would be:


SomeObject -> Serialize | -> IValueWriter.WriteInt32
                        | -> IValueWriter.WriteInt64

How would one accomplish this in a nice and clean fashion? What I am truly aiming for is basically a MethodInfo[] of the calls made in a specific implementation of an interface method.


Yes, you can do this using reflection. I wouldn't really call it "runtime" when none of the code being analyzed is running.

  1. Iterate all types in the assembly.
  2. Filter for types implementing ISerializable
  3. Find the method implementing ISerializable.Serialize
  4. Fetch the IL
  5. Look for callvirt instructions where the method token matches a method within IValueWriter.

There's an open source project, ILSpy, which should be a good example of how to decode IL instructions and look for method calls.


cleanest way is AOP. take a look to PostSharp

All you need to do is to create some Attributes and add them to your methods, to be logged, etc.

as far as I know they manipulate the IL after compilation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜