如何将Objective-C静态库绑定到Xamarin.iOS?

我已经阅读了Xamarin的文档。

这是Objective-C中的testing类:

#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; } 

当我运行应用程序,我得到这个exception: 在这里输入图像说明

TestBinding属性为空。 我一定在某个地方出了问题,那我该怎么解决呢?

我写了一篇非常详细的博客文章,关于从去年的ObjC代码创build一个静态库,在Xamarin.iOS绑定项目上工作,你可以在这里find它(以防万一:wink :: wink :)。

这就是说,如果你已经有一个胖的静态库在你手中,它已经添加到你的Xamarin.iOS绑定项目如下所示:

绑定图像

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

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

它肯定会丢失一些有关fat库支持的体系结构的重要信息(它缺less第二个参数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来提供我们的LinkWith属性支持的i386 armv7 x86_64 arm64 ,如下所示:

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

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


另一件我会build议双重检查是你的静态库( libFoo.a在我的情况下)的Build Action正确设置为ObjcBindingNativeLibrary如显示在这里:

绑定图像

希望这可以帮助!