Skip to content

Instantly share code, notes, and snippets.

@zimnyaa
Created January 12, 2022 14:19
Show Gist options
  • Save zimnyaa/10eca1d805297520c57eb8a7170a4a39 to your computer and use it in GitHub Desktop.
Save zimnyaa/10eca1d805297520c57eb8a7170a4a39 to your computer and use it in GitHub Desktop.
Execute CLR assembly in the current process and redirect its output to file. Can be compiled and used as a Python module.
import winim/clr
import os
import nimpy
#Create dup handles
proc dup(oldfd: FileHandle): FileHandle {.importc, header: "unistd.h".}
proc dup2(oldfd: FileHandle, newfd: FileHandle): cint {.importc,
header: "unistd.h".}
# thanks Clonk from https://forum.nim-lang.org/t/6909
proc executeassembly(assembly_bytes: openarray[byte], args: openarray[string], tmpname: string) : string {.exportpy.} =
# input redirection begins
let tmpFileName = getTempDir() & tmpname
var stdout_fileno = stdout.getFileHandle()
var stdout_dupfd = dup(stdout_fileno)
var tmp_file: File = open(tmpFileName, fmWrite)
var tmp_file_fd: FileHandle = tmp_file.getFileHandle()
# dup2 tmp_file_fd to stdout_fileno -> writing to stdout_fileno now writes to tmp_file
discard dup2(tmp_file_fd, stdout_fileno)
#actual execution
var dotnetargs = toCLRVariant(args, VT_BSTR)
var assembly = load(assembly_bytes)
assembly.EntryPoint.Invoke(nil, toCLRVariant([dotnetargs]))
# input redirection ends
tmp_file.flushFile()
tmp_file.close()
discard dup2(stdout_dupfd, stdout_fileno)
result = readFile(tmpFileName)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment