gpt4 book ai didi

C# CreatePipe() -> protected 内存错误

转载 作者:行者123 更新时间:2023-11-30 15:11:18 25 4
gpt4 key购买 nike

我尝试使用 C# 创建管道。代码非常简单,但是当执行带有 CreatePipe() 调用的行时,我得到一个 System.AccessViolationException 并显示以下错误消息:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

这是我表单的完整代码:

public partial class Form1 : Form
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public DWORD nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}

public Form1()
{
InitializeComponent();
}

private void btCreate_Click(object sender, EventArgs e)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = (DWORD)System.Runtime.InteropServices.Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = IntPtr.Zero;
sa.bInheritHandle = true;

SafeFileHandle hWrite = null;
SafeFileHandle hRead = null;

if (CreatePipe(out hRead, out hWrite, sa, 4096))
{
MessageBox.Show("Pipe created !");
}
else
MessageBox.Show("Error : Pipe not created !");
}
}

在顶部我声明:using DWORD = System.UInt32;

如果有人能提供帮助,非常感谢。

最佳答案

protected 内存冲突的原因是因为 CreatePipe 的 Windows API 需要一个指向内存区域的指针值,该函数将用作安全属性结构的跳板。简单地传入 SECURITY_ATTRIBUTES 结构将覆盖安全内存(页面尚未分配给您的应用程序),因此出现 protected 内存错误。

传入一个 IntPtr 来表示这个指针,解决了你的问题。

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CreatePipe(ref IntPtr hReadPipe, ref IntPtr hWritePipe, IntPtr lpPipeAttributes, int nSize);

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public DWORD nLength;
public IntPtr lpSecurityDescriptor;
[MarshalAs(UnmanagedType.Bool)]
public bool bInheritHandle;
}

public Form1()
{
InitializeComponent();
}

private void btnCreate_Click(object sender, EventArgs e)
{

SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = (DWORD)System.Runtime.InteropServices.Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = IntPtr.Zero;
sa.bInheritHandle = true;

IntPtr attr = Marshal.AllocHGlobal(Marshal.SizeOf(sa));
Marshal.StructureToPtr(sa, attr, true);

IntPtr hWrite = new IntPtr();
IntPtr hRead = new IntPtr();

if (CreatePipe(ref hRead, ref hWrite, attr, 4096))
{
MessageBox.Show("Pipe created !");
}
else
{
int error = Marshal.GetLastWin32Error();
MessageBox.Show("Error : Pipe not created ! LastError= " + error);
}
}

关于C# CreatePipe() -> protected 内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com