Omri Gazitt
Omri Gazitt

Reputation: 3518

Can't get MonoTouch binding library to work

I can't even get the simplest kind of binding library to work - I must be doing something fundamentally wrong...

I created an Xcode project called “TestLib” that looks like this:

//  TestLib.h
#import <Foundation/Foundation.h>
@interface TestLib : NSObject
{
    NSString *status;
}
@property (nonatomic,retain) NSString *status;
@end

//  TestLib.m
#import "TestLib.h"
@implementation TestLib
@synthesize status;
- (id)init
{
    self = [super init];
    if (self) {
        [self setStatus:@"initialized"];
    }

    return self;
}
@end

The project is here: http://dl.dropbox.com/u/31924320/TestLib.tar.gz

I compiled this into “libTestLib.a”.

Then I created the simplest binding library I could (along with a “single view application” to test it), which simply initializes the TestLib class and calls the getter for the status property. I added the library (libTestLib.a) into the binding library so it has the LinkWith file / assembly directive. The ApiDefinition.cs file looks like this:

namespace TestLibBinder
{
      [BaseType(typeof(NSObject))]
      interface TestLib
      {
            [Export("status")]
            string Status { get; set; }
      }
}

That project is here: http://dl.dropbox.com/u/31924320/BindingTest.tar.gz

Unfortunately I get a null reference back from the library when I try to get the Status property…

        public override void ViewDidLoad ()
        {
              base.ViewDidLoad ();

              TestLib testLib = new TestLib();  // succeeds!
              string status = testLib.Status;  // got a null reference

              if (status != null)
                    label.Text = status;
              else
                    label.Text = "binding failed";                  
        }

Upvotes: 0

Views: 1061

Answers (1)

Omri Gazitt
Omri Gazitt

Reputation: 3518

I got this to work by stepping away from the Binding Library project approach and instead basing my code on the BindingSample in the xamarin sample suite.

Anyone who wants to build a C# binding to objective-C code using MonoTouch should really start by reviewing the Makefile in that project. The approach it outlines is:

  1. Explicitly compile the Objective-C code for the three architectures (ARM6, ARM7, i386)
  2. Use lipo to create a single universal static library
  3. Use btouch to create the DLL and include the static library through the assembly directive (LinkWith) - see AssemblyInfo.cs in that project - as well as in the btouch commandline through the --link-with option.

I personally found the process of creating the ApiDefinition.cs wrapper to be fairly straightforward, but there are some common mistakes - e.g. forgetting the trailing colon on a selector that takes one parameter.

Upvotes: 3

Related Questions