0

如何调用像StartXpsPrintJob这样的方法,该方法可以选择返回指向 COM 对象的指针,具体取决于是否为 OUT 参数传递了 NULL。

C++ 中的示例是使用printTicketStreamset的调用NULL

IXpsPrintJob *job = NULL;
IXpsPrintJobStream *jobStream = NULL;
hr = StartXpsPrintJob(
            printerName,
            NULL,
            NULL,
            NULL,
            completionEvent,
            NULL,
            0,
            &job,
            &jobStream,
            /* _Out_  IXpsPrintJobStream **printTicketStream */ NULL);

我知道我可以制作可选参数IntPtr,而不是out IntPtr仅仅 pass IntPtr.Zero,但这需要此函数的四个 P/Invoke 签名来包含所有选项,更不用说调用代码的样子了。

4

1 回答 1

0

由于参数实际上是指向将保存结果的指针的指针,因此分配一个指针并将其作为IntPtr.

示例签名:

[DllImport("XpsPrint.dll", EntryPoint = "StartXpsPrintJob", PreserveSig = false)]
private static extern void StartXpsPrintJob(
    // other parameters omitted for brevity
    IntPtr printTicketStream);

示例使用:

IXpsPrintJobStream ticketStream = null;
bool getTicketStream = false;

IntPtr ppTicketStream = IntPtr.Zero;
if (getTicketStream)
{
    ppTicketStream = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
    Marshal.StructureToPtr(IntPtr.Zero, ppTicketStream, false);
}

StartXpsPrintJob(ppTicketStream);

if (getTicketStream)
{
    IntPtr pTicketStream = (IntPtr)Marshal.PtrToStructure(ppTicketStream, typeof(IntPtr));
    ticketStream = (IXpsPrintJobStream)Marshal.GetTypedObjectForIUnknown(pTicketStream, typeof(IXpsPrintJobStream));
    Marshal.FreeCoTaskMem(ppTicketStream);
}

//ticket stream now has the result from StartXpsPrintJob or null, if it was not requested
于 2013-05-24T23:35:59.493 回答