Monotouch binding - “Cannot cast from source type

2019-08-03 01:23发布

问题:

I am a newbie on Monotouch. Recently, I am working on a Monotouch binding project that binds a custom iOS framework that developed myself into a .NET framework library. I follow the instructions on Xamarin but currently I am having an issue that cannot be resolved. This is my code.

**HEADER FILE IN OBJECTIVE C**

*GRG.h*
@interface GRG: NSObject {} 

// Shared instance 
+ (GRG*) sharedG; 

// Preference class 
@property (nonatomic, readonly) GRGPreferences  *preferences; 

// Driver version 
@property (readonly,copy) NSString* driverVersion; 

// More parameters... 
@end 

*GRGPreferences.h*
@interface GRGPreferences : NSObject <GRGPreferencesProtocol>{} 

// Enable DEBUG 
@property BOOL debugEnabled; 

// More parameters... 
@end 

*GRGPreferencesProtocol.h*
@protocol GRGPreferencesProtocol <NSObject>  

// More parameters... 
@end 

I convert my header file into this

**API DEFINITION**

[BaseType (typeof (NSObject))] 
interface GRG 
{ 
        [Static][Export("sharedG")] 
        GRG SharedG{ get; } 

        [Export("preferences")] 
        GRGPreferences Preferences{ get;} 

        [Export("driverVersion", ArgumentSemantic.Copy)] 
        string DriverVersion {get;} 
} 

[BaseType (typeof (GRGPreferencesProtocol))] 
public interface GRGPreferences 
{ 
        [Export("debugEnabled")] 
        bool DebugEnabled{ get; set;} 
} 

[BaseType(typeof (NSObject))] 
[Model] 
public interface GRGPreferencesProtocol 
{} 

After that, I created a test app on mono to test the newly created library and get access to the values I created. However, I got an error.

Console.WriteLine(GRG.sharedG.DriverVersion); - This works fine. It returns the proper value.

GRGPreferences pref = GRG.SharedG.Preferences; - Error : "Cannot cast from source type to destination type."

Console.WriteLine(GRG.sharedG.Preferences.DebugEnabled); - Error : "Cannot cast from source type to destination type."

Can anyone please help me?

回答1:

From a quick look I think this is what you want:

[BaseType (typeof (NSObject))] 
public interface GRGPreferences : GRGPreferencesProtocol {

Your GRGPreferences type inherits from NSObject while implementing the protocol you want.