我已经将Star Micronics SDK绑定到我的Xamarin应用程序。我的应用程序随机崩溃,但出现以下错误:
SIGABRT - 'PortException', reason: 'Native WritePort failed'我的绑定方法如下所示:
[BaseType (typeof (NSObject))]
public partial interface SMPort {
//...
[Export ("writePort:::")]
Int32 WritePort (IntPtr writeBuffer, int offSet, int size);
}我称它为:
private static void Print(NSMutableData commandsToPrint) {
try {
//...
int count = printerPort.WritePort (test, 0, Convert.ToInt32(dataBytes.Length));
} catch (Exception e) {
//...
} finally {
//Release the port
SMPort.ReleasePort (printerPort);
}原始C库的Objective-C实现捕获了一个PortException异常:
@try
{
[starPort writePort:dataToSentToPrinter :totalAmountWritten :remaining];
}
@catch (PortException *exception)
{
//...
}
@finally
{
//...
}我如何在我的Xamarin应用程序中捕获相同的异常,以便我可以处理异常并阻止应用程序崩溃?
发布于 2014-11-11 19:03:34
从托管代码中捕获Objetive-C异常不是一种受支持的方案1,有时可能会工作,有时则不会。
在您的特定情况下,最简单的解决方案是将第三方本机库包装在另一个库(您自己编写)中,这会将Objective-C异常转换为任何其他错误报告机制(例如,返回错误代码)。
所以在C语言中,你会得到这样的结果:
int call_writeport (SMPort *starPort, void *dataToSendToPrinter, int totalAmountWritten, int remaining)
{
@try
{
[starPort writePort:dataToSentToPrinter :totalAmountWritten :remaining];
return 0;
}
@catch (PortException *exception)
{
return 1;
}
}在C#中,您可以将其绑定为DllImport:
[DllImport ("__Internal")]
static extern int call_writeport (SMPort port, IntPtr writeBuffer, int offset, int size);和用法:
if (call_writeport (port.Handle, writeBuffer, offset, size) != 0)
Console.WriteLine ("Writing to port failed");我选择编写一个C方法(并使用P/Invoke进行绑定)是任意的,您可以很容易地创建一个Objective-C类并将其绑定到您的绑定项目中。
1 Apple强烈建议不要将Objective-C异常用于任何情况,除非是最致命的情况,这就是为什么我们没有优先修复它的原因。
https://stackoverflow.com/questions/26850450
复制相似问题