Powershell: Add-Type with unsafe compilation flag. error CS0227

Created on 8 Sep 2020  Â·  3Comments  Â·  Source: PowerShell/PowerShell

I am trying to start a well working PS 5 cmdlet.

PS-snipped

=================

$cp = New-Object CodeDom.Compiler.CompilerParameters
$cp.CompilerOptions ='/unsafe'

$CSource=@"
using System;
using System.IO;

public class ISOFile
{
public unsafe void Create(string Path, object Stream, int BlockSize, int TotalBlocks)
{
int bytes = 0;
byte[] buf = new byte[BlockSize];
var ptr = (System.IntPtr)(&bytes);
var o = System.IO.File.OpenWrite(Path);
var i = Stream as System.Runtime.InteropServices.ComTypes.IStream;

if (o != null) { 
  while (TotalBlocks-- > 0) {  
    i.Read(buf, BlockSize, ptr); o.Write(buf, 0, bytes);  
  }  
  o.Flush(); o.Close();  
}

}
}
"@

if (!('ISOFile' -as [type])) 
{  
   Add-Type -TypeDefinition $CSource   -Language CSharp  -CompilerOptions $cp  -Verbose -PassThru
}

### here comes an error
<#
Add-Type -TypeDefinition $CSource -Language CSharp -Verbose -P …
| ~~~~~~~~~~~~~~
| (7,22): error CS0227: Unsicherer Code wird nur angezeigt, wenn mit /unsafe kompiliert wird. public unsafe void Create(string Path, object Stream, int BlockSize, int TotalBlocks)

Add-Type -TypeDefinition $CSource -Language CSharp -Verbose -P …
| ~~~~~~~~~~~~~~
| Cannot add type. Compilation errors occurred.

>

=================

The same code is running on PS 5 without errors.
It must be something wrong with compiler flags.

Would you like to help me, please?

Thanks!
jan

Issue-Question Resolution-Answered

Most helpful comment

It's a different compiler so the parameter is a little different:

Add-Type -CompilerOptions '-unsafe' -TypeDefinition $CSource

All 3 comments

It's a different compiler so the parameter is a little different:

Add-Type -CompilerOptions '-unsafe' -TypeDefinition $CSource

Yes, now Roslyn is used, CodeDom is deprecated.

Thanks! It does work, now.
jan

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ajensenwaud picture ajensenwaud  Â·  3Comments

manofspirit picture manofspirit  Â·  3Comments

rkeithhill picture rkeithhill  Â·  3Comments

lzybkr picture lzybkr  Â·  3Comments

JohnLBevan picture JohnLBevan  Â·  3Comments