IntPtr转换为结构单点触摸
本文关键字:单点 触摸 结构 转换 IntPtr | 更新日期: 2023-09-27 18:20:25
我绑定到目标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);