I am trying to bind the types of an Objective-C library using btouch. I have managed to compile my API definition file with btouch and have successfully called methods that return no parameters or which return basic parameters like string or integer. However, when I try call methods that return instance objects for other classes defined in the API definition file, I get an exception System.InvalidCastException thrown. So in the example listing that follows, the static OpenConnection method of the UltraliteManager class throws this exception when called from a MonoTouch project.
This is the Objective-C header file:
#import <Foundation/Foundation.h>
@interface UltraliteConnection : NSObject {
@private
void * ulconnection;
}
- (id) initWithULConnection: (void*) connect;
- (void) dealloc;
- (void) close;
- (void) executeStatement: (NSString*) sql;
@end
@interface UltraliteManager: NSObject {}
+ (void) initialize;
+ (void) fini;
+ (UltraliteConnection*) openConnection: (NSString*)connectionParms;
@end
This is the Objective-C implementation (abridged to show just the relevant implementations):
@implementation UltraliteConnection
- (id) initWithULConnection: (void*) connect
{
[super init];
ulconnection = connect;
[self retain];
return self;
}
- (void) dealloc
{
[super dealloc];
}
- (void) close
{
ULError error;
((ULConnection*) ulconnection)->Close(&error);
[self release];
}
@end
@implementation UltraliteManager
+ (UltraliteConnection*) openConnection: (NSString*)connectionParms
{
ULError error;
ULConnection * connbase;
UltraliteConnection * connwrap;
connbase = ULDatabaseManager::OpenConnection([connectionParms UTF8String],
&error,
NULL);
connwrap = [[UltraliteConnection alloc] initWithULConnection:connbase];
[connwrap release];
return connwrap;
}
@end
And this is the API definition file:
using MonoTouch.Foundation;
namespace Ultralite {
[BaseType (typeof (NSObject))]
interface UltraliteConnection {
[Export("close")]
void Close ();
[Export("executeStatement:")]
void ExecuteStatement(string sql);
}
[BaseType (typeof (NSObject))]
interface UltraliteManager {
[Static, Export ("initialize")]
string Initialize ();
[Static, Export ("fini")]
void Fini ();
[Static, Export ("openConnection:")]
UltraliteConnection OpenConnection (string connectionParms);
}
}
I have found that if I return NULL from my implementation of openConnection (ie. replace the line return connwrap; with return nil;) then the method returns without throwing an exception. So it seems to me that this exception has to do with returning of the UltraliteConnection object to MonoTouch.
Anyone have any idea what is causing this problem and how I can resolve it?