Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit05482e5

Browse files
committed
Make RunString safer and more standard.
1 parenta2d6024 commit05482e5

File tree

1 file changed

+40
-19
lines changed

1 file changed

+40
-19
lines changed

‎src/runtime/pythonengine.cs

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -411,33 +411,54 @@ public static PyObject ModuleFromString(string name, string code)
411411
/// executing the code string as a PyObject instance, or null if
412412
/// an exception was raised.
413413
/// </remarks>
414-
publicstaticPyObjectRunString(stringcode)
414+
publicstaticPyObjectRunString(
415+
stringcode,IntPtr?globals=null,IntPtr?locals=null
416+
)
415417
{
416-
IntPtrglobals=Runtime.PyEval_GetGlobals();
417-
IntPtrlocals=Runtime.PyDict_New();
418-
419-
IntPtrbuiltins=Runtime.PyEval_GetBuiltins();
420-
Runtime.PyDict_SetItemString(locals,"__builtins__",builtins);
418+
boolborrowedGlobals=true;
419+
if(globals==null)
420+
{
421+
globals=Runtime.PyEval_GetGlobals();
422+
if(globals==IntPtr.Zero)
423+
{
424+
globals=Runtime.PyDict_New();
425+
Runtime.PyDict_SetItemString(
426+
globals.Value,"__builtins__",
427+
Runtime.PyEval_GetBuiltins()
428+
);
429+
borrowedGlobals=false;
430+
}
431+
}
421432

422-
IntPtrflag=(IntPtr)257;/* Py_file_input */
423-
IntPtrresult=Runtime.PyRun_String(code,flag,globals,locals);
424-
Runtime.XDecref(locals);
425-
if(result==IntPtr.Zero)
433+
boolborrowedLocals=true;
434+
if(locals==null)
426435
{
427-
returnnull;
436+
locals=Runtime.PyDict_New();
437+
borrowedLocals=false;
428438
}
429-
returnnewPyObject(result);
430-
}
431439

432-
publicstaticPyObjectRunString(stringcode,IntPtrglobals,IntPtrlocals)
433-
{
434440
IntPtrflag=(IntPtr)257;/* Py_file_input */
435-
IntPtrresult=Runtime.PyRun_String(code,flag,globals,locals);
436-
if(result==IntPtr.Zero)
441+
442+
try
437443
{
438-
returnnull;
444+
IntPtrresult=Runtime.PyRun_String(
445+
code,flag,globals.Value,locals.Value
446+
);
447+
448+
if(Runtime.PyErr_Occurred()!=0)
449+
{
450+
thrownewPythonException();
451+
}
452+
453+
returnnewPyObject(result);
454+
}
455+
finally
456+
{
457+
if(!borrowedLocals)
458+
Runtime.XDecref(locals.Value);
459+
if(!borrowedGlobals)
460+
Runtime.XDecref(globals.Value);
439461
}
440-
returnnewPyObject(result);
441462
}
442463
}
443464

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp