How to Add Code at the Entry of Every Function

How to add code at the entry of every function?

Depending on what you're hoping to achieve as a result of this you can sort of make something (easily enough for free functions or static member functions) in C++ with functor objects which wrap real calls, e.g.:

#include <iostream>

template<void f(void)>
struct Wrap {
void operator()() const {
std::cout << "Pre call hook" << std::endl;
f();
}
};

namespace {
void test_func() {
std::cout << "Real function" << std::endl;
}
}

const Wrap<&test_func> wrapped_test_func = {};

int main() {
wrapped_test_func();
return 0;
}

Clearly this needs some more work to be generic enough e.g. C++0x variadic templates or lots of overloads. Making it work nicely with member functions is also more fiddly.

I've sketched an outline for a (non-intrusive) way of doing this for member functions too:

#include <iostream>

template<class C, void (C::*F)()>
class WrapMem {
C& inst;
public:
WrapMem(C& inst) : inst(inst) {}

void operator()() {
std::cout << "Pre (method) call hook" << std::endl;
((inst).*(F))();
}

void operator()() const {
std::cout << "Pre (method, const) call hook" << std::endl;
((inst).*(F))();
}
};

class Foo {
public:
void method() { std::cout << "Method called" << std::endl; }
void otherstuff() {}
};

class FooWrapped : private Foo {
public:
FooWrapped() : method(*this) {}
using Foo::otherstuff;
WrapMem<Foo,&Foo::method> method;
};

int main() {
FooWrapped f;
f.otherstuff();
f.method();
return 0;
}

You could also skip the private inheritance and using to expose non-wrapped methods, but you need to be careful about destructors and it's easy to accidentally bypass if you do that. (e.g. implicit cast for reference to base). The non-intrusive way is also limited to only working for the public interface and not for internal calls either.

With C++11 you can get perfect forwarding and also reduce the construction of the wrapping objects to a simple macro that takes the class and member function name and deduces the rest for you, e.g.:

#include <iostream>
#include <utility>

template <typename Ret, typename ...Args>
struct Wrapper {
template <class C, Ret (C::*F)(Args...)>
class MemberFn {
C& inst;
public:
MemberFn(C& inst) : inst(inst) {}
MemberFn& operator=(const MemberFn&) = delete;

Ret operator()(Args&& ...args) {
return ((inst).*(F))(std::forward<Args>(args)...);
}

Ret operator()(Args&& ...args) const {
return ((inst).*(F))(std::forward<Args>(args)...);
}
};
};

template <typename T>
struct deduce_memfn;
template <typename C, typename R, typename... Args>
struct deduce_memfn<R (C::*)(Args...)> {
template <R(C::*F)(Args...)>
static typename Wrapper<R, Args...>::template MemberFn<C, F> make();
};

template <typename T>
decltype(deduce_memfn<T>()) deduce(T);

template <typename T>
struct workaround : T {}; // Clang 3.0 doesn't let me write decltype(deduce(&Class::Method))::make...

#define WRAP_MEMBER_FN(Class, Method) decltype(workaround<decltype(deduce(&Class::Method))>::make<&Class::Method>()) Method = *this

class Foo {
public:
Foo(int);
double method(int& v) { return -(v -= 100) * 10.2; }
void otherstuff();
};

class WrappedFoo : private Foo {
public:
using Foo::Foo; // Delegate the constructor (C++11)
WRAP_MEMBER_FN(Foo, method);
using Foo::otherstuff;
};

int main() {
WrappedFoo f(0);
int i = 101;
std::cout << f.method(i) << "\n";
std::cout << i << "\n";
}

(Note: this deduction won't work with overloads)
This was tested with Clang 3.0.

add a single line of code in each function in visual studio

You don't need to hack up your code to get function instrumentation! See here for example: http://www.drdobbs.com/automatic-code-instrumentation/184403601

The short story is that MSVC has _penter, a facility for doing pretty much what you're trying to accomplish here, but without modifying most of the source code.

As an aside, a standard term for what you asked about (adding code before function calls) is Aspect Oriented Programming.

Is there a tool that enables me to insert one line of code into all functions and methods in a C++-source file?

Try Aspect C++ (www.aspectc.org). You can define an Aspect that will pick up every method execution.

In fact, the quickstart has pretty much exactly what you are after defined as an example:
http://www.aspectc.org/fileadmin/documentation/ac-quickref.pdf

Run Code Before Every Function Call for a Class in C++

AspectC++ is what you want. I haven't used it myself, but Aspect-Oriented Programming paradigm tries to solve this exact problem.

Automatically running code at the start of every C function

Since you have tagged with gcc it has the -finstrument-functions option:

Generate instrumentation calls for entry and exit to functions. ...

Any way to add code to every function call

You could try something like this:

for( var x in window) {
if( typeof window[x] == "function") {
(function(x) {
var ox = window[x];
window[x] = function() {
console.log(x);
ox.apply(null,arguments);
};
})(x);
}
}

However, this would only work on global functions, not functions of objects or scoped functions. It's also kind of a nuke, so is a poor substitute for manually adding console logging to the specific functions you want to call.

Instead it would probably be better to insert a breakpoint in the code (using the browser's developer tools) and checking the call stack at that point.

Add unique code to start and end of function in c

If You are using GCC, look at -finstrument-functions switch - see https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-finstrument-functions It basically calls user-defined function upon entering and leaving any called function. This has some advantages:

  • You don't have to modify Your functions at all.
  • Your code is called no matter how the function exitted (You can have any number of return in Your function and don't care)

Adding console.log to every function automatically

Here's a way to augment all functions in the global namespace with the function of your choice:

function augment(withFn) {
var name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
return fn.apply(this, arguments);

}
})(name, fn);
}
}
}

augment(function(name, fn) {
console.log("calling " + name);
});

One down side is that no functions created after calling augment will have the additional behavior.

Adding code to a javascript function programmatically

If someFunction is globally available, then you can cache the function, create your own, and have yours call it.

So if this is the original...

someFunction = function() {
alert("done");
}

You'd do this...

someFunction = (function() {
var cached_function = someFunction;

return function() {
// your code

var result = cached_function.apply(this, arguments); // use .apply() to call it

// more of your code

return result;
};
})();

Here's the fiddle


Notice that I use .apply to call the cached function. This lets me retain the expected value of this, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.



Related Topics



Leave a reply



Submit