2013-06-28 34 views
0

我必須綁定一個客觀的C庫:的IntPtr轉換到一個struct MonoTouch的

[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);如何轉換狀態int一個結構體...我嘗試過編組,但是會產生一個錯誤。其他一切看起來都是正確的 - 就像我能夠讓打印機進行一點點打印,即使它們是隨機字符一樣我假設我的程序實際上是與打印機通信的 - 這意味着綁定和庫是一切運作良好...它剛開的IntPtr一個struct的問題...

回答

2

最簡單的方法可能是聲明爲一個指向結構的結合:

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

,然後就像這樣使用它:

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

Thanks!現在測試! – jharr100