Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd304a5c

Browse files
authored
Merge pull request#12 from jbw3/csharp-examples
Adding more C# examples
2 parentsa4e4ddd +c7c7379 commitd304a5c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎README.md

Lines changed: 56 additions & 0 deletions
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+
publicclassPerson
543+
{
544+
publicPerson(stringfirstName,stringlastName)
545+
{
546+
FirstName=firstName;
547+
LastName=lastName;
548+
}
549+
550+
publicstringFirstName {get;set; }
551+
publicstringLastName {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+
Personperson=newPerson("John","Smith");
563+
564+
// acquire the GIL before using the Python interpreter
565+
using (Py.GIL())
566+
{
567+
// create a Python scope
568+
using (PyScopescope=Py.CreateScope())
569+
{
570+
// convert the Person object to a PyObject
571+
PyObjectpyPerson=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+
stringcode="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)

[8]ページ先頭

©2009-2025 Movatter.jp