Skip to content

Commit cefba0e

Browse files
author
jbw3
committed
Adding more C# examples
1 parent a4e4ddd commit cefba0e

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

README.md

+62-1
Original file line numberDiff line numberDiff line change
@@ -517,13 +517,74 @@ which may be called at startup without having acquired the GIL.
517517

518518
When finished using Python APIs, managed code must call a corresponding
519519
`PythonEngine.ReleaseLock` to release the GIL and allow other threads
520-
to use Python.
520+
to use Python:
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:
531+
532+
```csharp
533+
using (Py.GIL())
534+
{
535+
PythonEngine.Exec("doStuff()");
536+
}
537+
```
521538

522539
The AcquireLock and ReleaseLock methods are thin wrappers over the
523540
unmanaged `PyGILState_Ensure` and `PyGILState_Release` functions from
524541
the Python API, and the documentation for those APIs applies to
525542
the managed versions.
526543

544+
## Passing C# Objects to the Python Engine
545+
546+
This section demonstrates how to pass a C# object to the Python runtime.
547+
The example uses the following `Person` class:
548+
549+
```csharp
550+
public class Person
551+
{
552+
public Person(string firstName, string lastName)
553+
{
554+
FirstName = firstName;
555+
LastName = lastName;
556+
}
557+
558+
public string FirstName { get; set; }
559+
public string LastName { get; set; }
560+
}
561+
```
562+
563+
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:
567+
568+
```csharp
569+
// create a person object
570+
Person person = new Person("John", "Smith");
571+
572+
// acquire the GIL before using the Python interpreter
573+
using (Py.GIL())
574+
{
575+
// convert the Person object to a PyObject
576+
PyObject pyPerson = person.ToPython();
577+
578+
// create a Python variable "person"
579+
PyDict locals = new PyDict();
580+
locals["person"] = pyPerson;
581+
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);
585+
}
586+
```
587+
527588
## License
528589

529590
Python for .NET is released under the open source MIT License.

0 commit comments

Comments
 (0)