Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
Python.NET documentation
Python.NET documentation

Contents:

Back to top

Codecs

Python.NET performs some conversions between .NET and Python automatically.For example, when Python calls this C# method:

voidFoo(intbar){...}

viaFoo(42), Python value42 of typeint will beautomatically converted to .NET typeSystem.Int32. Another way toinvoke those conversions is to calldotNetObject.ToPython()(available as an extension method) orpyObject.As<T>() to convertPyObject to .NET.

An incomplete list of Python types, that are converted between Pythonand .NET automatically: most numeric types,bool,string,Nullable<T> to itsValue orNone and back, etc.

A custom conversion (Codec) can be defined by implementing one of the (orboth) interfaces:

  • Python.Runtime.IPyObjectDecoder to marshal Python objects to .NET

interfaceIPyObjectDecoder{boolCanDecode(PyObjectobjectType,System.TypetargetType);boolTryDecode<T>(PyObjectpyObj,outTvalue);}
  • Python.Runtime.IPyObjectEncoder to marshal .NET objects to Python

interfaceIPyObjectEncoder{boolCanEncode(System.Type);PyObjectTryEncode(System.Object);}

Once implemented, instances have to be registered withPython.Runtime.PyObjectConversions.RegisterEncoder/-Decoder. Onecan overridesome of the default conversions by registering newcodecs.

Codec priorities

When multiple codecs are registered, the runtime will first try the ones, thatwere registered earlier. If you need to have some grouping of codecs bypriority, create and exposePython.Runtime.Codecs.EncoderGroup/-.DecoderGroup. For example:

publicstaticEncoderGroupHighPriorityEncoders{get;}=newEncoderGroup();voidInit(){PyObjectConversions.RegisterEncoder(HighPriorityEncoders);varlowPriorityEncoder=newSomeEncoder();PyObjectConversions.RegisterEncoder(lowPriorityEncoder);}...sometimelaterHighPriorityEncoders.Add(newSomeOtherEncoder());
On this page

[8]ページ先頭

©2009-2025 Movatter.jp