python - Create object from string repesentation in C API -
i working on system embedding python interpreter, , need construct pyobject*
given string c api.
i have const char*
representing dictionary, in proper format eval()
work within python, ie: "{'bar': 42, 'baz': 50}"
.
currently, being passed python pyobject*
using py_unicode_
api (representing string), in python interpreter, can write:
foo = eval(myobject.value) print(foo['bar']) # prints 42
i change automatically "eval" const char*
on c side, , return pyobject*
representing completed dictionary. how go converting string dictionary in c api?
there 2 basic ways this.
the first call eval
same way in python. trick need handle builtins
module, because don't free in c api. there number of ways this, 1 easy way import it:
/* or pyeval_getbuiltins() if know you're @ interpreter's top level */ pyobject *builtins = pyimport_importmodule("builtins"); pyobject *eval = pyobject_getattrstring(builtins, "eval"); pyobject *args = py_buildvalue("(s)", expression_as_c_string); pyobject *result = pyobject_call(eval, args);
(this untested code, , @ least leaks references, , doesn't check null return if want handle exceptions on c side… should enough idea across.)
one nice thing can use ast.literal_eval
in same way eval
(which means free validation); change "builtins"
"ast"
, , "eval"
"literal_eval"
. real win you're doing eval
in python, know wanted.
the alternative use compilation apis. @ high level, can build python statement out of "foo = eval(%s)"
, pyrun_simplestring
it. below that, use py_compilestring
parse , compile expression (you can parse , compile in separate steps, isn't useful here), pyeval_evalcode
evaluate in appropriate globals , locals. (if you're not tracking globals yourself, use interpreter-reflection apis pyeval_getlocals
, pyeval_getglobals
.) note i'm giving super-simplified version of each function; want use 1 of sibling functions. can find them in docs.
Comments
Post a Comment