Result of Python calls to C++

Here's the place for discussion related to coding in FreeCAD, C++ or Python. Design, interfaces and structures.
toral
Posts: 2
Joined: Fri May 18, 2018 1:21 pm

Result of Python calls to C++

Postby toral » Fri May 18, 2018 1:27 pm

Hello,
How can we get the result of Base::Interpreter().runString (or runStringArg, runStringObject etc..) to C++ side?

e.g;

std::string result = Base::Interpreter().runString("1+1") // result NONE
std::string result = Base::Interpreter().runString("print 3") // result NONE

Base::Interpreter().runString("a = 1+1") // result NONE
std::string result = Base::Interpreter().runString("a") // result NONE

Thank you for your help,
jmaustpc
Posts: 8747
Joined: Tue Jul 26, 2011 6:28 am
Location: Australia

Re: Result of Python calls to C++

Postby jmaustpc » Fri May 18, 2018 1:40 pm

Hi, I deleted your other post because it appeared to only be a duplication, feel free to post again if I missed something.
DeepSOIC
Posts: 5525
Joined: Fri Aug 29, 2014 12:45 am
Location: Saint-Petersburg, Russia

Re: Result of Python calls to C++

Postby DeepSOIC » Fri May 18, 2018 2:59 pm

/// Run a statement on the python interpreter and return back the result object.
Py::Object runStringObject(const char *sCmd);
wmayer
Site Admin
Posts: 12707
Joined: Thu Feb 19, 2009 10:32 am

Re: Result of Python calls to C++

Postby wmayer » Fri May 18, 2018 7:49 pm

Base::Interpreter().runString("a = 1+1") // result NONE
In this case Py::Object runStringObject(const char *sCmd) doesn't work because it raises an exception. Instead you should use Base::Interpreter().getValue:

Code: Select all

Base::Interpreter().getValue("a = 1+1", "a")
toral
Posts: 2
Joined: Fri May 18, 2018 1:21 pm

Re: Result of Python calls to C++

Postby toral » Mon May 21, 2018 5:36 am

DeepSOIC wrote:
Fri May 18, 2018 2:59 pm
/// Run a statement on the python interpreter and return back the result object.
Py::Object runStringObject(const char *sCmd);
I've spend hell of a time try to work this one, but it throws exception also crashes visual studio too.


wmayer wrote:
Fri May 18, 2018 7:49 pm
Base::Interpreter().runString("a = 1+1") // result NONE
In this case Py::Object runStringObject(const char *sCmd) doesn't work because it raises an exception. Instead you should use Base::Interpreter().getValue:

Code: Select all

Base::Interpreter().getValue("a = 1+1", "a")
And yes.. Finally, thank you Sir!

This works very well. I got the result as string like below. For the other ones that face with this issue too.

Code: Select all

	PyObject* result = Base::Interpreter().getValue("result = 1.02+1.2", "result");
	PyObject* objectsRepresentation = PyObject_Repr(result);
	const char* str = PyString_AsString(objectsRepresentation);