Marshal.StructureToPtr模块ntdll.dll中失败(Marshal.Struc

2019-08-02 23:39发布

我会带着几分历史的开始:我面对这个问题目前突然出现没有任何修改代码。 然后以同样的方式消失后3天。 现在回来了一个星期,不希望走=)。

我有一个带打印机的工作原理码 -设置它的打印机首选项来打印指定方式的文件。 我用它指向网络打印机(它是这样的任务,共同的办法,因为我知道)的TCP地址本地打印机。

在这里如下用于加载从二进制文件打印机配置代码 (先前保存在类似的方式)。 我给带的非托管函数调用声明的所有源代码,因为不知道会引起问题。 即制动我的应用程序(Windows服务)线路:

Marshal.StructureToPtr(pInfo, pPInfo, true); //THIS LINE FAILS

这里是一个函数的整个代码:

public static bool LoadSettings(string printerName, string filepath)
{
    Logger.GetLog().WriteInformation(string.Format("Loading printer settings '{0}' for printer '{1}'", filepath, printerName), "PrinterSettingsStorage.LoadSettings()");
    bool success = false;
    try
    {
        if (!File.Exists(filepath))
        {
            return false;
        }

        IntPtr hPrinter;
        int bytes = 0;
        IntPtr pPInfo;
        IntPtr pDevMode;
        PRINTER_INFO_2 pInfo = new PRINTER_INFO_2();

        PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
        PrinterValues.pDatatype = 0;
        PrinterValues.pDevMode = 0;
        PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;

        //retrieve the devmode from file
        using (FileStream fs = new FileStream(filepath, FileMode.Open))
        {
            int length = Convert.ToInt32(fs.Length);
            pDevMode = GlobalAlloc(0, length);
            for (int i = 0; i < length; i++)
            {
                Marshal.WriteByte(pDevMode, i, (byte)fs.ReadByte());
            }
        }

        //get printer handle
        OpenPrinter(printerName, out hPrinter, ref PrinterValues);

        //get bytes for printer info structure and allocate memory
        GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out bytes);
        if (bytes == 0)
        {
            throw new Exception("Get Printer Failed");
        }
        pPInfo = GlobalAlloc(0, bytes);

        //set pointer to printer info
        GetPrinter(hPrinter, 2, pPInfo, bytes, out bytes);

        //place the printer info structure
        pInfo = (PRINTER_INFO_2)Marshal.PtrToStructure(pPInfo, typeof(PRINTER_INFO_2));

        //insert the new devmode
        pInfo.pDevMode = pDevMode;
        pInfo.pSecurityDescriptor = IntPtr.Zero;

        //set pointer to new printer info
        Marshal.StructureToPtr(pInfo, pPInfo, true); //THIS LINE FAILS

        //update
        SetPrinter(hPrinter, 2, pPInfo, 0);

        //free resources
        GlobalFree(pPInfo);
        GlobalFree(pDevMode);
        ClosePrinter(hPrinter);

        success = true;
    }
    catch (COMException ce)
    {
        Logger.GetLog().WriteError(string.Format("COM error loading printer settings to printer: {0}", Marshal.GetLastWin32Error()), ce.StackTrace, "PrinterSettingsStorage.LoadSettings()");
    }
    catch (Exception e)
    {
        Logger.GetLog().WriteError(string.Format("Unknown error loading printer settings to printer"), e.StackTrace, "PrinterSettingsStorage.LoadSettings()");
    }
    finally
    {
        Logger.GetLog().WriteInformation(string.Format("Finish loading printer settings '{0}' for printer '{1}'. Success: {2}", printerName, filepath, success), "PrinterSettingsStorage.LoadSettings()");
    }
    return success;
}

[StructLayout(LayoutKind.Sequential)]
internal struct PRINTER_DEFAULTS
{
    public int pDatatype;
    public int pDevMode;
    public int DesiredAccess;
}

[StructLayout(LayoutKind.Sequential)]
internal struct PRINTER_INFO_2
{
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pServerName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPrinterName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pShareName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPortName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pDriverName;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pComment;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pLocation;
    public IntPtr pDevMode;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pSepFile;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pPrintProcessor;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pDatatype;
    [MarshalAs(UnmanagedType.LPStr)]
    public readonly string pParameters;
    public IntPtr pSecurityDescriptor;
    public readonly Int32 Attributes;
    public readonly Int32 Priority;
    public readonly Int32 DefaultPriority;
    public readonly Int32 StartTime;
    public readonly Int32 UntilTime;
    public readonly Int32 Status;
    public readonly Int32 cJobs;
    public readonly Int32 AveragePPM;
}

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GlobalFree(IntPtr handle);

[DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true,
    CharSet = CharSet.Ansi, ExactSpelling = true,
    CallingConvention = CallingConvention.StdCall)]
private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel,
                                        IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);

[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA",
    SetLastError = true, CharSet = CharSet.Ansi,
    ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool
    OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter,
                out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);

[DllImport("winspool.drv", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern bool SetPrinter(IntPtr hPrinter, int Level, IntPtr pPrinter, int Command);

[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true,
    ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool ClosePrinter(IntPtr hPrinter);

症状:

  • 服务简单地停止在参考线之后立即退出。 没有finally块执行,没有例外抓获。

  • Windows事件日志包含错误

    错误模块名称:ntdll.dll中,版本:6.1.7601.17725,时间戳:0x4ec49b8f异常代码:0xc0000374错误偏移:0x000ce6c3出错进程ID:0x12dc错误的应用程序启动时间:0x01cdc71b9bf9b661错误的应用程序路径:C:\ Program Files文件(x86)的\ MyServiceExePath.exe错误模块路径:C:\ WINDOWS \ Syswow64资料\ ntdll.dll中的报告ID:0eb45111-330f-11E2-be8e-005056975a30

我的操作系统:Windows Server 2008 R2。

正如我所说的,它不断地再现了一段时间,然后一旦走了,而不在代码中的任何改变。 我不知道是什么原因导致这个问题,为什么会这样不稳定。 希望以后还有人在这里,更expirienced与非托管代码比我=)。

有任何想法吗?

Answer 1:

        //insert the new devmode
        pInfo.pDevMode = pDevMode;
        pInfo.pSecurityDescriptor = IntPtr.Zero;

        //Add by me
        Marshal.StructureToPtr(pInfo, pPInfo, false);
        //set pointer to new printer info 
        Marshal.StructureToPtr(pInfo, pPInfo, true);

        //update
        SetPrinter(hPrinter, 2, pPInfo, 0);
        //Add by me
        Marshal.DestroyStructure(pPInfo, typeof(PRINTER_INFO_2));

        //free resources
        GlobalFree(pPInfo);
        GlobalFree(pDevMode);
        ClosePrinter(hPrinter);


文章来源: Marshal.StructureToPtr fails in module ntdll.dll