Marshal.StructureToPtr在模块ntdll.dll中失败

时间:2012-11-20 15:06:45

标签: c# marshalling unmanaged

我将从一段历史开始:我目前遇到的问题突然出现而没有对代码进行任何更改。然后在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);

症状:

  • 服务只是立即停止在参考线上退出。没有最终的块执行,没有异常被捕获。

  • Windows事件日志包含错误

    错误模块名称:ntdll.dll,版本:6.1.7601.17725,时间戳:0x4ec49b8f 异常代码:0xc0000374 故障偏移:0x000ce6c3 错误进程id:0x12dc 错误应用程序启动时间:0x01cdc71b9bf9b661 错误的应用程序路径:C:\ Program Files(x86)\ MyServiceExePath.exe 错误模块路径:C:\ Windows \ SysWOW64 \ ntdll.dll 报告编号:0eb45111-330f-11e2-be8e-005056975a30

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

正如我所说,它会在一段时间内不断重现,然后一旦离开而没有任何代码更改。我不知道是什么导致了这个问题,为什么它如此不稳定。希望这里有人,对我的非托管代码更加满意=)。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

        //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);
相关问题