@@ -519,11 +519,67 @@ When finished using Python APIs, managed code must call a corresponding
519
519
` PythonEngine.ReleaseLock ` to release the GIL and allow other threads
520
520
to use Python.
521
521
522
+ A ` using ` statement may be used to acquire and release the GIL:
523
+
524
+ ``` csharp
525
+ using (Py .GIL ())
526
+ {
527
+ PythonEngine .Exec (" doStuff()" );
528
+ }
529
+ ```
530
+
522
531
The AcquireLock and ReleaseLock methods are thin wrappers over the
523
532
unmanaged ` PyGILState_Ensure ` and ` PyGILState_Release ` functions from
524
533
the Python API, and the documentation for those APIs applies to
525
534
the managed versions.
526
535
536
+ ## Passing C# Objects to the Python Engine
537
+
538
+ This section demonstrates how to pass a C# object to the Python runtime.
539
+ The example uses the following ` Person ` class:
540
+
541
+ ``` csharp
542
+ public class Person
543
+ {
544
+ public Person (string firstName , string lastName )
545
+ {
546
+ FirstName = firstName ;
547
+ LastName = lastName ;
548
+ }
549
+
550
+ public string FirstName { get ; set ; }
551
+ public string LastName { get ; set ; }
552
+ }
553
+ ```
554
+
555
+ In order to pass a C# object to the Python runtime, it must be converted to a
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:
559
+
560
+ ``` csharp
561
+ // create a person object
562
+ Person person = new Person (" John" , " Smith" );
563
+
564
+ // acquire the GIL before using the Python interpreter
565
+ using (Py .GIL ())
566
+ {
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 ();
572
+
573
+ // create a Python variable "person"
574
+ scope .Set (" person" , pyPerson );
575
+
576
+ // the person object may now be used in Python
577
+ string code = " fullName = person.FirstName + ' ' + person.LastName" ;
578
+ scope .Exec (code );
579
+ }
580
+ }
581
+ ```
582
+
527
583
## License
528
584
529
585
Python for .NET is released under the open source MIT License.
0 commit comments