2016-04-20 23 views
2

我已閱讀Xamarin的文檔。如何將Objective-C靜態庫綁定到Xamarin.iOS?

這是我的測試類在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屬性爲空。 我一定在某個地方出了問題,所以我該如何解決?

+0

你有沒有嘗試客觀Sharpie? https://developer.xamarin.com/guides/cross-platform/macios/binding/objective-sharpie/ – iamIcarus

+0

嘗試使用'string'綁定而不是'NSString'。如果這不起作用,出於某種原因,本地庫很可能沒有鏈接到可執行文件中(構建日誌會顯示這一點)。 –

+0

我嘗試使用字符串而不是NSString,但這不正確。現在我想也許我的本地庫有些問題,我會檢查它。感謝您的建議。 –

回答

2

我寫了一篇關於從ObjC代碼去創建一個靜態庫的非常詳細的博客文章,該文章適用於Xamarin.iOS綁定項目,您可以找到它here(以防萬一:wink :: wink :)。

話雖這麼說,如果你已經在你的手中脂肪靜態庫,它已添加到您的Xamarin.iOS綁定項目如下所示:

binding image

問題可能是你的libxyz.linkwith.cs缺少一些信息,如果它看起來像這樣:

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

它肯定是缺少有關你的脂肪庫支持的體系結構的一些重要信息(它丟失第二個參數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屬性支持的拱形,如下所示:

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

希望這有助於!

+0

我很抱歉回答太晚。這非常有幫助,謝謝。 –

+0

如果它解決了你的問題,你可以將其標記爲答案:)很高興它幫助你 – dalexsoto