【问题标题】:Catch exception from bound library从绑定库中捕获异常
【发布时间】:2015-01-07 03:35:03
【问题描述】:

我已将 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 应用程序中捕获相同的异常,以便处理异常并阻止应用程序崩溃?

【问题讨论】:

    标签: ios binding xamarin.ios xamarin


    【解决方案1】:

    从托管代码中捕获 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 异常用于除最致命的场景之外的任何情况,这就是为什么我们没有将其作为最终修复的高优先级。

    【讨论】:

    • 谢谢罗尔夫。 writePort 方法实际上返回一个 int,我需要访问它。我将如何处理这种情况?
    • 您可以在函数签名中添加一个'out'参数来返回错误代码。
    猜你喜欢
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多