簡體   English   中英

IntPtr轉換為struct monotouch

[英]IntPtr conversion to a struct monotouch

我綁定了一個目標c庫:

[Export ("getParsedStatus::")]
[CompilerGenerated]
public virtual void GetParsedStatus (IntPtr starPrinterStatus, global::System.UInt32 level)
{
    if (IsDirectBinding) {
        Definition.Messaging.void_objc_msgSend_StarPrinterStatus_UInt32 (this.Handle, selGetParsedStatus_Handle, starPrinterStatus, level);
    } else {
        Definition.Messaging.void_objc_msgSendSuper_StarPrinterStatus_UInt32 (this.SuperHandle, selGetParsedStatus_Handle, starPrinterStatus, level);
    }
}

原始目標c庫函數的位置如下:

(void)getParsedStatus:(void *)starPrinterStatus :(u_int32_t)level;

一切似乎都在使用我的C#代碼:

SMPort port = null;
Byte[] commands = null;
uint totalAmountWritten = 0;
uint commandSize=0;
StarPrinterStatus_2 stat;
IntPtr status;
private void test()
{
    try{
        stat = new StarPrinterStatus_2();

        port = new SMPort(new NSString("BT:PRNT Star"), new NSString("mini"), 10000);

        status = Marshal.AllocHGlobal(Marshal.SizeOf(stat));

        port.GetParsedStatus( status ,(uint) 2);
        Marshal.PtrToStructure(status, stat);
        port.BeginCheckedBlock(status, (uint) 2);

        commands = new byte[]{0x1b, 0x40, 0x1b, 0x2d, 0x31, 0x1b, 0x45, 0x00, 0x1b, 0x7b, 0x00, 0x1d, 0x42, 0x00, 0x1d, 0x21, 0x31,0x1d, 0x4c, 0x00, 0x00, 0x1b, 0x61, 0x31, 0xA, 0xA, 0xA };

        IntPtr ptr2 = Marshal.AllocHGlobal(commands.Length*4);

        int i = 0;
        foreach(byte b in commands)
        {
            Marshal.WriteByte(ptr2,i*4, b);
        }

        totalAmountWritten = 0;
        commandSize = (uint)commands.Length;

        //while (totalAmountWritten < commandSize)
        //foreach(byte b in commands)
        //{
            uint remaining = commandSize - totalAmountWritten;
            uint amountWritten = port.WritePort(ptr2, totalAmountWritten, remaining);
            totalAmountWritten += amountWritten;
        //}

        port.EndCheckedBlock(status, (uint) 2);

        //Marshal.FreeHGlobal(status);
    //  Marshal.FreeHGlobal(ptr2);
        Port.ReleasePort(port);

    }
    catch(Exception ex) {
        MessageBox.Show (ex.Message, "Error", MessageBoxButton.OK);
    }
}

但是,當我調用時,讓我們說port.GetParsedStatus( status ,(uint) 2); 如何將狀態轉換為結構...我已經嘗試了編組但是會產生錯誤。 其他一切似乎都正常工作 - 因為我能夠讓打印機進行一點點打印,即使它們是隨機字符我假設我的程序實際上是與打印機通信 - 這意味着綁定和庫是一切運作良好......只需將IntPtr轉換為結構...

最簡單的方法可能是將綁定聲明為結構的指針:

 public void GetParsedStatus (ref StarPrinterStatus_2 starPrinterStatus, uint level);

然后就像這樣使用它:

 port.GetParsedStatus (ref stat, (uint) 2);

暫無
暫無

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

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