-2

if I meet a struct where there is a pointer to a function, how may I make a deep copy of this

I have already reviewed Deep copy of a pointer function. But the thing is that I want to make a socket and send it to other machines. The solution purposed by this discussion will not work. Since the memory where store this function will not exist in the new machine.

E.G code:

struct A {
int (*f)()
};

int func() {
return 10;
}

int main() {
struct A;
A.f = &func;
// how can I send a socket includes the information of A
}
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 3
    You basically want another machine to willingly accept and execute arbitrary machine code? What could possibly go wrong. – Igor Tandetnik Jun 22 '19 at 03:35
  • @IgorTandetnik: That's only a problem if the connection is insufficiently authenticated. – Ben Voigt Jun 22 '19 at 03:38
  • 1
    What does "deep copy of a functional pointer" mean? Also, your question title says "C", but this is tagged "C++" (not that this question makes much sense for either one). – jamesdlin Jun 22 '19 at 03:41
  • 2
    you need to look into [serialization](https://stackoverflow.com/questions/234724/is-it-possible-to-serialize-and-deserialize-a-class-in-c) if you want to communicate a complex structure through a socket – kmdreko Jun 22 '19 at 03:51
  • 1
    You can't. The pointer value is meaningless on the other machine. You need to invent a serialization schema. – selbie Jun 22 '19 at 03:51
  • You're basically trying to do [remote procedure calls](https://en.wikipedia.org/wiki/Remote_procedure_call). That's a whole subject in and of itself. – Etienne de Martel Jun 22 '19 at 03:52

1 Answers1

2

There is no reasonable way to do this in C or C++ -- even if you copied the memory corresponding to the function you wanted to send across the socket, it is likely to contain references to other portions of code in memory (either in your application or in shared libraries) which were not copied.

About the only way of doing this I can think of would be to compile the function into a shared library and send the shared library file across the socket. However, this will place restrictions on the code involved, and may still not work if the library has dependencies which aren't available on the remote system.

Whatever you are doing… you will need to consider alternatives. There's probably a better way of doing this.