簡體   English   中英

使用可選的輸出指針進行P /調用

[英]P/Invoke with optional out pointer

如何調用類似StartXpsPrintJob的方法,該方法根據是否為OUT參數傳遞了NULL,有選擇地返回一個指向COM對象的指針。

在C ++中,示例是將printTicketStream設置為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而只是傳遞IntPtr.Zero ,但這需要該函數的四個P / Invoke簽名來包含所有選項,更不用說調用代碼的樣子了。

由於參數實際上是指向將保存結果的指針,因此分配一個指針並將其作為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM