I want to create a ios plugin for unity. The function is send textmessage using some sdk. Well, here is my object c:
-(TextMessage*) CsendText:(NSString *)number CmsgContent:(NSString *)msg{
return [MessagingApi sendText:(NSString*) number msgContent:(NSString *) msg]
}
and here is my c wrap code :
TextMessage* SendMessage(const char* contactNumber,const char* content){
Messaging* msg = [[Messaging alloc] init];
NSString* nr = [NSString stringWithUTF8String:contactNumber];
NSString* contentText = [NSString stringWithUTF8String:content];
TextMessage* newText = [msg CsendText:nr CmsgContent:contentText];
return newText;
}
you can see i return a textmessage, it is an event not a char,, how can i pass the event to unity,
my c# code is here:
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern string SendMessage (string contactNumber,string content);
#endif
string phoneNumber="";
string content="";
void OnGUI () {
phoneNumber = GUI.TextField ( new Rect (250, 125, 250, 25), phoneNumber, 40);
content = GUI.TextField (new Rect (250, 157, 250, 25), content, 40);
if (GUI.Button(new Rect (250, 250, 100, 30),"click me")) {
SendMessage(phoneNumber,content);
}
}
That's not the way it is working. You cannot just return something in C and expect it to appear in Unity / C#. To achieve a "two way communication" you'll need to do the following.
C# code
[DllImport ("__Internal")]
private static extern void _SomeCMethod(string parameter);
(Objective-) C code
void _SomeCMethod(const char *parameter)
{
}
When you invoke _SomeMethod
in C#, _SomeMethod
in your (Objective-) C code gets called.
Objective-C code
- (void)callSomeCSharpMethod
UnitySendMessage("GO", "SomeCSharpMethod", "parameter");
}
C# code (MonoBehaviour
script attached to GO
)
void SomeCSharpMethod(string parameter)
{
}
When you invoke callSomeCSharpMethod
in Objective-C, SomeCSharpMethod
in your C# code gets called.
You'll have to convert your NSString
s to c strings (const char *
) and vice versa.
const char *
=> NSString
[NSString stringWithCString:string encoding:NSUTF8StringEncoding];
NSString
=> const char *
[string cStringUsingEncoding:NSUTF8StringEncoding];
Note:
This is just a simple example on how to achieve a two way communication channel between C# and native iOS code.
Of course you don't want to hardcode e.g. the GameObject
's name in your code, so you can just pass that name (for callbacks from Objective-C) to your native iOS code at the very beginning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With