Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Adding more C# examples #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 21, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -519,11 +519,67 @@ When finished using Python APIs, managed code must call a corresponding
`PythonEngine.ReleaseLock` to release the GIL and allow other threads
to use Python.

A `using` statement may be used to acquire and release the GIL:

```csharp
using (Py.GIL())
{
PythonEngine.Exec("doStuff()");
}
```

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

## Passing C# Objects to the Python Engine

This section demonstrates how to pass a C# object to the Python runtime.
The example uses the following `Person` class:

```csharp
public class Person
{
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}

public string FirstName { get; set; }
public string LastName { get; set; }
}
```

In order to pass a C# object to the Python runtime, it must be converted to a
`PyObject`. This is done using the `ToPython()` extension method. The `PyObject`
may then be set as a variable in a `PyScope`. Code executed from the scope
will have access to the variable:

```csharp
// create a person object
Person person = new Person("John", "Smith");

// acquire the GIL before using the Python interpreter
using (Py.GIL())
{
// create a Python scope
using (PyScope scope = Py.CreateScope())
{
// convert the Person object to a PyObject
PyObject pyPerson = person.ToPython();

// create a Python variable "person"
scope.Set("person", pyPerson);

// the person object may now be used in Python
string code = "fullName = person.FirstName + ' ' + person.LastName";
scope.Exec(code);
}
}
```

## License

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