c# - 如何将 Objective-C 静态库绑定(bind)到 Xamarin.iOS?

标签 c# ios objective-c binding xamarin.ios

我已阅读 Xamarin 的文档。

这是我在 Objective-C 中的测试类:

#import "XamarinBundleLib.h"

@implementation XamarinBundleLib

+(NSString *)testBinding{
    return @"Hello Binding";
}
@end

非常简单,就一个方法。

这是我的 C# 类:

namespace ResloveName
{
    [BaseType (typeof (NSObject))]
    public partial interface IXamarinBundleLib {
        [Static,Export ("testBinding")]
        NSString TestBinding {get;}
    }
}

然后这是我的 AppDelegate 代码:

public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            string testStr = ResloveName.IXamarinBundleLib.TestBinding.ToString ();
            System.Console.WriteLine ("testStr="+testStr);

            return true;
        }

当我运行应用程序时,出现以下异常: enter image description here

TestBinding 属性为空。 我一定是哪里错了,那么我该如何解决呢?

最佳答案

去年我写了一篇关于从 ObjC 代码创建静态库的非常详细的博客文章,适用于 Xamarin.iOS 绑定(bind)项目,您可以找到它 here (以防万一 :wink::wink:)。

话虽如此,如果您手中已有一个胖静态库,并且它已添加到您的 Xamarin.iOS 绑定(bind)项目中,如下所示:

binding image

问题可能是您的 libxyz.linkwith.cs 缺少一些信息,如果它看起来像这样:

using ObjCRuntime;
[assembly: LinkWith ("libFoo.a", SmartLink = true, ForceLoad = true)]

它肯定缺少一些关于你的fat库支持的架构的重要信息(它缺少第二个参数target),你可以使用以下命令来检索你当前的静态库支持哪些架构

xcrun -sdk iphoneos lipo -info path/to/your/libFoo.a

你应该得到这样的输出

Architectures in the fat file: Foo/libFoo.a are: i386 armv7 x86_64 arm64

所以我们知道这个静态库支持 i386 armv7 x86_64 arm64 并且我们应该通过提供第二个参数 target 如下:

using ObjCRuntime;
[assembly: LinkWith ("libFoo.a", LinkTarget.ArmV7 | LinkTarget.Arm64 | LinkTarget.Simulator | LinkTarget.Simulator64, SmartLink = true, ForceLoad = true)]

还要确保 LinkWith 属性的第一个参数与您的静态库文件名(在我的例子中为“libFoo.a”)匹配。


我建议仔细检查的另一件事是静态库(在我的例子中是 libFoo.a)的 Build Action 是否正确设置为 ObjcBindingNativeLibrary 如下所示:

binding image

希望这对您有所帮助!

关于c# - 如何将 Objective-C 静态库绑定(bind)到 Xamarin.iOS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733584/

相关文章:

ios - swift 3,JSON,写入时无效的顶级类型

ios - APS 缺少权利

ios - 自定义推送过渡不起作用,而相同的自定义呈现过渡有效

objective-c - 使用Swift的TFHpple框架进行编译错误

c# - StreamReader 文件如何仅在列表框中达到高分时更新?

c# - 字典中类型的自定义相等比较器

c# - 什么是 DLR 层职责?

c# - 如何获取变量属性值?

ios - 应用程序打开时,如何在 iOS 中获取到达的远程通知数组?

objective-c - 在 Objective-C 中取消引用指针