IntPtr转换为struct monotouch

时间:2013-06-28 21:22:29

标签: c# xamarin.ios xamarin

我绑定了一个目标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转换为结构......

1 个答案:

答案 0 :(得分:2)

最简单的方法可能是将绑定声明为结构的指针:

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

然后就这样使用它:

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