@@ -517,17 +517,9 @@ which may be called at startup without having acquired the GIL.
517
517
518
518
When finished using Python APIs, managed code must call a corresponding
519
519
` PythonEngine.ReleaseLock ` to release the GIL and allow other threads
520
- to use Python:
520
+ to use Python.
521
521
522
- ``` csharp
523
- IntPtr gilState = PythonEngine .AcquireLock ();
524
-
525
- PythonEngine .Exec (" doStuff()" );
526
-
527
- PythonEngine .ReleaseLock (gilState );
528
- ```
529
-
530
- A ` using ` statement may also be used to acquire and release the GIL:
522
+ A ` using ` statement may be used to acquire and release the GIL:
531
523
532
524
``` csharp
533
525
using (Py .GIL ())
@@ -561,9 +553,9 @@ public class Person
561
553
```
562
554
563
555
In order to pass a C# object to the Python runtime, it must be converted to a
564
- ` PyObject ` . This is done using the ` ToPython ` extension method. The ` PyObject `
565
- may then be added to a dictionary of local variables and passed to the
566
- ` PythonEngine.Exec ` function :
556
+ ` PyObject ` . This is done using the ` ToPython() ` extension method. The ` PyObject `
557
+ may then be set as a variable in a ` PyScope ` . Code executed from the scope
558
+ will have access to the variable :
567
559
568
560
``` csharp
569
561
// create a person object
@@ -572,16 +564,19 @@ Person person = new Person("John", "Smith");
572
564
// acquire the GIL before using the Python interpreter
573
565
using (Py .GIL ())
574
566
{
575
- // convert the Person object to a PyObject
576
- PyObject pyPerson = person .ToPython ();
567
+ // create a Python scope
568
+ using (PyScope scope = Py .CreateScope ())
569
+ {
570
+ // convert the Person object to a PyObject
571
+ PyObject pyPerson = person .ToPython ();
577
572
578
- // create a Python variable "person"
579
- PyDict locals = new PyDict ();
580
- locals [" person" ] = pyPerson ;
573
+ // create a Python variable "person"
574
+ scope .Set (" person" , pyPerson );
581
575
582
- // the person object may now be used in Python
583
- string code = " fullName = person.FirstName + ' ' + person.LastName" ;
584
- PythonEngine .Exec (code , null , locals .Handle );
576
+ // the person object may now be used in Python
577
+ string code = " fullName = person.FirstName + ' ' + person.LastName" ;
578
+ scope .Exec (code );
579
+ }
585
580
}
586
581
```
587
582
0 commit comments