C does not have any methods (only functions), so your question is meaningless in C.
In C++11, assuming the method to be changed is virtual
, and assuming your C++ implementation is using a vtable pointer located at start of the object (this is often the case with GCC on Linux), and if both old and new classes have the same size and are using single inheritance from a common base class (e.g. FooBase
), you could use the placement new
operator, so in your main program:
class FooBase {
virtual ~FooBase();
virtual int bar(int);
/// etc
}
class ProgramFoo : public FooBase {
virtual ~ProgramFoo();
virtual int bar (int);
/// other fields and methods
};
and in your plugin:
class PluginFoo : public FooBase {
virtual ~ProgramFoo();
virtual int bar (int);
/// other fields and methods
static_assert(sizeof(PluginFoo) == sizeof(ProgramFoo),
"invalid PluginFoo size");
};
then you might have some plugin function like
extern "C" FooBase*mutate_foo(ProgramFoo*basep)
{
basep->~ProgramFoo(); // destroy in place, but don't release memory
return new(basep) PluginFoo(); // reconstruct in same place
}
it hopefully would override the old vptr by the new one.
but this smells bad, is probably undefined behavior according to the C++11 standard, but might work on some C++ implementations, and is certainly implementation specific. I don't recommend coding that way, even if it might sometimes happen to "work".
The idiomatic way would be to use member function pointers or C++11 closures.
It looks like your plugin architecture is wrongly designed. Look into Qt plugins for some good inspiration.