Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark mode
clr-loader documentation
clr-loader documentation

Contents:

Back to top

Usage#

Getting a runtime#

To get aRuntime instance, one of theget_* functions has to becalled. There are currently the factory functionsget_mono(),get_coreclr() andget_netfx(). All of these provide variousconfiguration options that are documented in theReference.They also provide reasonable defaults and can be called without parameters ifthe respective runtime is installed globally:

fromclr_loaderimportget_coreclrruntime=get_coreclr()

After this, the runtime will usually already be initialized. The initializationis delayed for .NET Core to allow adjusting the runtime properties beforehand.

Information on the runtime, its version and parameters can be retrieved usingruntime.info() (seeRuntime.info()).

Getting a callable function#

A wrapped assembly can be retrieved from the runtime by callingRuntime.get_assembly() with the path.

The following example class is provided in the repository:

usingSystem.Text;usingSystem.Runtime.InteropServices;usingSystem;namespaceExample{publicclassTestClass{publicstaticintTest(IntPtrarg,intsize){varbuf=newbyte[size];Marshal.Copy(arg,buf,0,size);varbufAsString=Encoding.UTF8.GetString(buf);varresult=bufAsString.Length;Console.WriteLine($"Called {nameof(Test)} in {nameof(TestClass)} with {bufAsString}, returning {result}");Console.WriteLine($"Binary data: {Convert.ToBase64String(buf)}");returnresult;}}}

Assuming it has been compiled toout/example.dll, it can now be loaded usingRuntime.get_assembly():

assembly=runtime.get_assembly("path/to/assembly.dll")

Note

This doesnot guarantee that the DLL is already loaded and will notnecessarily trigger an error if that is not possible. Actually resolving theDLL only happens (for all implementations but Mono) when retrieving theconcrete function.

Theassembly instance can now be used to get a wrapper instance of theTest function in Python. The given parameters are the fully qualified classname and the function name. Alternatively, a single parameter can be provided,and we assume that the last “component” is the function name. These areequivalent:

function=assembly.get_function("Example.TestClass","Test")function=assembly.get_function("Example.TestClass.Test")

This function can now be called with a Pythonbinary like this:

result=function(b"testy mctestface")

TheIntPtr parameter in C# will now point directly at thebinary buffer,theint parameter will contain the size. The given call will thus result inthe output:

Called Test in TestClass with testy mctestface, returning 16Binary data: dGVzdHkgbWN0ZXN0ZmFjZQ==

result will now be16.

Warning

While the buffer can theoretically also be changed in the .NET function, thisis not tested.

On this page

[8]ページ先頭

©2009-2025 Movatter.jp