tags:

views:

342

answers:

5

Hi there.

I am currently researching how to write .NET code that can be injected into another .NET process and override function return values. The idea is that my code would alter the return values of a method call, like this:

Public Function DoSomething() As String

Return "Value"

End Function

My code would intercept calls to DoSomething() and return my own custom string, rather then "Value".

I'm guessing that I would need to look o using the .NET Profiling API to do this type of thing. Does anyone have experience of using the Profiling API, and if so, do you think that this code injection is possible?

I don't intend to use this for anything malicious, I'm just interested in trying something very low-level in .NET to see if it can be done.

Cheers. Jas.

A: 

You can do this using TypeMock Isolator.

I don't have TypeMock, but based on some of their examples, I think you could do it with something like this: (C# first, then I'll try to translate to VB)

using (RecordExpectations recorder = RecorderManager.StartRecording())
{
    DoSomething();
    recorder.Return("My Own Custom String");
}

Using recorder As RecordExpectations = RecorderManager.StartRecording()
    DoSomething
    recorder.Return("My Own Custom String")
End Using

Looks like TypeMock is free for open-source projects, otherwise it costs money. But they've already done the Profiling API coding for you, so you can worry about solving your problem, not about writing hairy C++.

Joe White
Thanks for the reply. I do happen own a licence for TypeMock and use it for unit testing, but my project is an actual .NET app. What I would like to do is write my own .NET app that could mimic TypeMock and inject my own code into another assembly and change it's function return values on the fly.
A: 

Detours is how you do it for Win32. I've never seen Detours.NET, but maybe something they are doing will give you a hint on how to implement what you are trying to do.

JP Alioto
A: 

You might investigate message sinks... This is an advanced area, but basically, it does exactly what you are trying to do, intercept a call frm one function to another, and during the interception, execute code of your own... The message sinks can be linked together, and can be written as send message sinks, to be processed as the call is initiated, or alternatively as receive sinks, to be processed on the other end

Here's a more detailed explanation

Charles Bretana
A: 

PostSharp can do this, but not at runtime, it modifies the code after it was originally written.

Jason Coyne
A: 

The CThru project that comes with Typemock Isolator can give you this functionallity.
The project is an open source but it uses Typemock Isolator.
It will let you register your callback method and change its behavior at runtime.
It is not limited to running with unit tests.
One thing to note is you'll get a performance hit once you'll use it.

Ohad Horesh