0

I have a python script which has two input arguments:

def main(a, b):
  c=a+b
  return c
if __name__ == '__main__':
 main(sys.argv[1], sys.argv[2])

on the other hand I have a c++ code which I need to call this script from one of my functions:

extern "C" std::string call_py(std::string a,std::string b) {
  ***how to call it and pass a and b to the script.py???***
 }

I call my script in console using python3 script.py "Hi" "Bye"

sama
  • 333
  • 2
  • 11
  • There is a Python>C binding (for C libs), but I am unaware of the other way round. Thus, I'd expect it is necessary to call the script (via commandline) from the C code and parse the result – Cpt.Hook Dec 05 '22 at 08:36
  • Potential duplicate: https://stackoverflow.com/questions/1056051/how-do-you-call-python-code-from-c-code – Cpt.Hook Dec 05 '22 at 08:37
  • Do you really want to call the script? It does not have any observable behavior, it does not print anything, it does not return anything specific. Or do you want to call the `main` function from your script, which does return something specific? – mch Dec 05 '22 at 08:38
  • extern "c" is because it is going to be a Mysql UDF thats why I have to use extern c in my c++ code, On the other hand, yes I want to call the script which runs main and in the main I am going to call main(a,b), It return c and the call_py is going to return the return value of script.py – sama Dec 05 '22 at 08:57
  • 1
    If you want to execute the script, you need some kind of interprocess communication. The simplest thing is probably to print your result to standard output and use `popen` from C++. If you just want to call `main`, you need to [embed an interpreter](https://docs.python.org/3/c-api/index.html). – molbdnilo Dec 05 '22 at 09:33
  • BTW: `extern "C"` makes little sense when the prototype involves C++ classes. – molbdnilo Dec 05 '22 at 09:35
  • @molbdnilo I think your comment makes sense. Can you help with the example code so I can test it? – sama Dec 05 '22 at 10:02
  • there is a `Python.h` header. So you can use `#include` to include it. I'm not exactly sure about the details, but there should be an easy way to run Python from C++. – J Muzhen Dec 05 '22 at 10:23
  • @JMuzhen yes I know there is I am looking for a sample code to using it. – sama Dec 05 '22 at 10:37

0 Answers0