Skip to content

Commit d304a5c

Browse files
authored
Merge pull request #12 from jbw3/csharp-examples
Adding more C# examples
2 parents a4e4ddd + c7c7379 commit d304a5c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

README.md

+56
Original file line numberDiff line numberDiff line change
@@ -519,11 +519,67 @@ When finished using Python APIs, managed code must call a corresponding
519519
`PythonEngine.ReleaseLock` to release the GIL and allow other threads
520520
to use Python.
521521

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+
522531
The AcquireLock and ReleaseLock methods are thin wrappers over the
523532
unmanaged `PyGILState_Ensure` and `PyGILState_Release` functions from
524533
the Python API, and the documentation for those APIs applies to
525534
the managed versions.
526535

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+
527583
## License
528584

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

0 commit comments

Comments
 (0)