How do I send or save a function and recv or restore a function and execute it in C++?

我与影子孤独终老i 提交于 2019-12-23 17:27:41

问题


Is there any way I can send or save a function as file? I want to do this in C++ on a Windows platform.

I assume that there is some convention between reader and sender or saver

Is it OK if I send like below? server side:

label1:
int func1(int somevar){
    int a = 1;
    return somevar+a;
}
label2:

send(sockfd, label2-label1, sizeof(int), 0) //send a size first
send(sockfd, label1, label2-label1, 0); // send a "function" 

thanks in advance!


回答1:


No, there's no way to do that in C++. Languages which could allow transfer of executable code include Erlang, Ruby, TCL.

Chris




回答2:


There already exists a mechanism for this in windows for C++. Your functions are "saved" when compiling in a dll. You can then "retrieve" your functions from the dll using GetProcAddress().




回答3:


With C++ this is definitely not possible.

You could send a precompiled dynamically linked library containing the functions and load and execeute them at the end point.




回答4:


C++ is a static language - you can't modify the executable you're running and add in new functions. Languages like Ruby would allow you to do this, but its just not a feature of C++.

You could, if really really needed, possibly put your function in a file, send it over the network, and have your program on the other end compile the file and run it with a popen from your process or something... but that's getting pretty ridiculous by that point.

I'd say redesign so you don't need this.




回答5:


YOU CAN DO IT! Just write your own compiler that instead of compiling files, it waits for signals, builds files, and then compiles them. And then possibly runs them.

Basically:

  1. send function text
  2. receive function text
  3. compile with your program the text
  4. execute the compiled code
  5. ???
  6. profit!



回答6:


No, that's not at all valid. That's basically quite impossible- you would need to use some sort of intermediary language or express the function in assembly or disassemble the resulting binary.



来源:https://stackoverflow.com/questions/7257476/how-do-i-send-or-save-a-function-and-recv-or-restore-a-function-and-execute-it-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!