我正在使用PowerShell Core编写P/Invoke代码,但失败了.
using System;
using System.Runtime.InteropServices;
public class Bindings
{
[DllImport("MyEncoder.dll")]
public static extern bool EncodeStream(
byte[] pbIn,
int cbIn,
ref byte pbOut,
out int cbOut);
}
C#代码如下:
var pbOut = new byte[pbIn.Length];
int cbOut = 0;
Bindings.EncodeStream(pbIn, pbIn.Length, ref pbOut[0], out cbOut);
它起作用了.
我的PowerShell代码是:
$Bindings = Add-Type -TypeDefinition $cs_code -PassThru
[byte[]]$pbIn = [IO.File]::ReadAllBytes("src.txt")
$cbIn = $pbIn.Length
$pbOut = [byte[]]::new($cbIn)
$cbOut = [int]0
# PowerShell 7.3.9
# Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
$Bindings::EncodeStream($pbIn, $cbIn, [ref]$pbOut[0], [ref]$cbOut)
我试着调试,发现$pbOut
$pbOut[0]
返回了GCHandle.AddrOfPinnedObject
个不同的地址.所以我想知道是不是$pbOut[0]
创建了新值,而PoewrShell引用了临时值.
任何帮助和测试都欢迎!