0

I wanted to try out embedding Python into C++. I was able to get that to work but I wanted to start writing prints with variables which are in declared in c++. For example:

(C++)

int num = 43;
PyRun_SimpleString("print("+num+")");
char g;
std::cin>>g;
PyRun_SimpleString("print("+g+")");

I tried to figure out how to use other related functions, but I don't seen to find enough information.

0

1 Answer 1

2

To pass char,

Python script:

def test(person):
    return "Hello " + person;

C++:

PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
pName = PyUnicode_FromString((char*)"script");
pModule = PyImport_Import(pName);
pFunc = PyObject_GetAttrString(pModule, (char*)"test");
pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"User"));
pValue = PyObject_CallObject(pFunc, pArgs);
auto result = _PyUnicode_AsString(pValue);
std::cout << result << std::endl;

Output:

Hello User

To pass integer it's the same like above. Here you are passing over double 2.0.

pArgs = PyTuple_Pack(1,PyFloat_FromDouble(2.0));
pValue = PyObject_CallObject(pFunc, pArgs);

You can refer to all the apis here >> https://docs.python.org/3/c-api/

Sign up to request clarification or add additional context in comments.

14 Comments

If you don't mind me asking but how would you use this? I'm not at all familiar with this.
I updated my code from initialization up till receiving results so it's easier. since you can run pyrunsimplestring, means your embedding has no issues. "script" is the name of your python file, script.py. while "test" is your function name. you can try it to understand
Thanks, but I'm running into an access violation reading location. Its being caused on the pFunc line. I set the py file; do I have to do anything with the module?
The pFunc line is loading the script. means possibly it's not able to find your script. make sure the naming is correct and the script location is within your environment. you can test it by adding the script on the same directory of your c++ exe OR you can set environment variable PATH for your user/admin to wherever your python file directory is.
Yes, I have my py file inside of the same folder location as my cpp file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.