Cocos2d-x + Lua access iOS Native SDK implementation scheme [go]

Source: Internet
Author: User

I believe many friends have encountered the problem of accessing the iOS native SDK when using Cocos2d-x+lua to develop the game, such as the common in-use payment SDK, the advertising SDK or some social Platform SDK, and so on, I have not received this kind of SDK. This article is mainly for I have done a project to access the iOS native SDK implementation of a summary, here to share, I hope to own and everyone's development work is helpful.

Before you expand the body, make a few notes:

1. The iOS native SDK I'm talking about is the SDK that was developed entirely in objective-c language for native iOS programming. Swift is very good and powerful, but I have not used, ashamed, but the language is only the expression of the way, the idea of solving the problem is the same;

2. This assumes that the main logic of the game is implemented using LUA, which is implemented using C + + for the main logic, as feasible in this article, and easier to design, then look down and see:)

3. This article takes the Quick-cocos2d-x 2.1 version as an example to explain, mainly because this is I previously did the project to use most one version, the X new version changes relatively big, but, still that sentence, solves the problem the idea is the same.

-------------------the beginning of the split line-------------------

All right, we're officially starting. Straight!

To solve this problem of access, in fact, the most important thing is to solve the problem of different language interaction, once the barrier of language interaction, the remaining things so easy!

As it relates to lua,c++,objective-c three languages, the problem appears to be complicated on the surface, but in fact only calmly (=. =) Combing, we can get the right idea.

Because the logic of our game is mostly implemented in Lua (as already assumed), and the SDK is implemented with OBJECTIVE-C, we need to address the interaction between Lua and Objective-c, where the ultimate goal is to "invoke" at the LUA level. Objective-c code (note that calls here are quoted, indirect calls), and when the OBJECTIVE-C plane receives the SDK callback, it notifies Lua. We know that LUA does not have an easy way to communicate directly with OBJECTIVE-C, but Lua can communicate through LUA binding and C + +, and we know that C + + and objective-c can be mixed, that C + + can be called directly (there are no quotes, Is the code that is really called directly) objective-c. Thinking about this is obvious, and we can use C + + as a bridge for Lua and objective-c interactions, and then to implement LUA-to-objective-c interactions.

Based on the above analysis, we can use the idea of expressing ourselves, where we divide the process of language interaction into 4 small parts:

The entire language interaction process can be summed up as: Lua calls LUA binding C + + interface, C + + interface calls a mixed Objective-c interface, and objective-c through the block form of callbacks, the results are notified to c++,c++ through Lua C The API returns the final result to Lua. the entire interaction between LUA and Objective-c is completed with this trip.

Simply say these 4 parts:

1.Lua Binding

The method of exporting the C + + interface to the LUA call is not expanded here because of its length, and you can refer to Lua's documentation as well as articles elsewhere on the web.

2. Mixed

One of the great advantages of objective-c is that it can be used in conjunction with C and C + +, just as there is a common implementation file in the same language. The specific mixed rules are not mentioned, here only two small details:

One, under Xcode the implementation file suffix is. mm, and cannot be. cpp or. m;

Two, a mixed implementation of the file reference header file place, C + + or C with # include, and objective-c with #import, mutual no impact.

3.Block Callback

Block is a great feature of objective-c, and even better is the ability to write C + + code directly inside the BLOCK: You can look at Apple's official documentation for details.

In fact, in the beginning, I have tried to use the way to send notifications to implement OBJECTIVE-C to C + + callback, that is, Objective-c received the SDK callback, to send the C + + part with callback information notification, Although there are ready-made notificationcenter in the cocos2d-x to help implement it, one obvious drawback of this approach is that it greatly increases the coupling between C + + code and OBJECTIVE-C code, and objective-c part of C + + calls C + + Notificationcenter Notice, C + + part also to mix objective-c code, call C + + Notificationcenter receive notice, this structure is really enough irritability.

By contrast, using block callbacks is a lot more neat, objective-c this way everything is pure, it does not need to know whether to be called by C + + or Objective-c call, do not need to spend a lot of effort on the return callback, only need to do their own job, Then call block at the appropriate time to get everything done.

4.Lua C API

The LUA C API is used to interact with LUA in the C/C + +, which has been encapsulated as a more user-friendly C + + Class API in Cocos2d-x. The point here is that when invoking the LUA function with this API, in order to pass the parameters, the arguments are required to stack, and the order of the stacks affects the order in which the LUA function takes the parameters, but fortunately the rules are simple: the first-in-stack arguments precede or The stacking order is the same as the argument order . For example, if the C + + side calls the LUA function Func, the order in which the stack is a,b,c is called the function func (a,b,c)

-------------------the split Line-------------------

In the course of the whole language interaction, if you think that Lua is the top layer and objective-c is the bottom level, then the process of interacting in the actual game is a top-down process, but we need to do it from the bottom up when implementing each level of code, because the logic in the top-level LUA code is determined by the interface and functionality of the underlying OBJECTIVE-C SDK. That is, we need to first according to the original OBJECTIVE-C interface in the SDK, do suitable for our game objective-c encapsulation proxy class, and then implement the C + + Bridge interface According to the package results, and then implement the corresponding logic of Lua .

According to the above analysis, from the hierarchical point of view, the design is as follows:

In addition to the LUA logic, the two most important things we need to implement: C + + Bridge class and Objective-c SDK Delegate class. The former is a bridge function of the interface class, in principle do not do any game logic related data processing, while the latter is responsible for encapsulating the original SDK interface, receive and preliminary processing SDK callback data. The implementation of the former depends on the implementation of the latter, and the implementation of the latter depends on the SDK. Finally, the data obtained by the SDK is passed through layers, which is given to Lua logic processing, which ultimately guarantees that the game logic of data processing is placed as much as possible into the LUA layer.

This design has many advantages, on the one hand, the top level of game logic changes, does not affect the underlying multi-language interaction code, on the other hand, the bottom of the SDK changes, such as version update or even replace, does not affect the upper game logic, multi-layered structure effectively reduce complexity, isolate the changes, for frequent demand changes, This structure can also guarantee the convenience of expansion.

Split-line--------------------------------------Summary

In summary, to solve the problem of access to iOS native SDK, the main need 4 steps:

1. Implement OBJECTIVE-C SDK Delegate Class according to SDK interface and function;

2. Implement the corresponding C + + Bridge class according to Objective-c SDK Delegate class;

3. Generate the corresponding LUA binding code according to C + + Bridge class;

4. Write Lua layer logic.

-------------------the last split line-------------------

Well, finally, again to the exciting part of the code: The following is an example of an iOS third-party billing SDK, to illustrate the implementation of access steps.

This SDK has only one header file GameBilling.h, the main use of the method and protocol are as follows: (to avoid the length of the reason, the comments and unnecessary code are deleted). I use code annotations to illustrate the purpose of each method.

1//Initialize Billing SDK 2 + (gamebilling *) initializegamebilling; 3  4//Tell the SDK the orientation of the game screen so that the SDK shows the correct UI 5-  (void) Setdialogorientationmask: (Uiinterfaceorientationmask) Orientationmask; 6  7//Confirm payment, show paid UI 8-(void) Dobillingwithuiandbillingindex: (NSString *) Billingindex isrepeated: (BOOL) isrepeated Cpparam: (nsstring*) Cpparam; 9//Delegate callback to tell the caller whether the payment was successful or not @protocol gamebillingdelegate<nsobject>12 @required13-(void) Onbillingresult: (billingresulttype) ResultCode billingindex: (NSString *) index message: (NSString *) message;14 @end

The first two methods are used to initialize the SDK, and there is little to do with the logic of the game, so we put the call to them at the beginning of the program without having to export it to LUA. The third method is used when the user confirms the payment and needs to be exported to Lua, which is called when the user makes a corresponding operation in the game interface. The last Delegate callback, we use the previously mentioned objective-c SDK Delegate Class to receive, and for preliminary processing, and then the block to C + + Bridge class.

OK, let's finish the Objective-c SDK Delegate Class first. Here the objective-c is made into a simple singleton to use, which may not actually be necessary.

First complete the header file, here named CMGCIAPiOS.h, as follows:

1 #import "GameBilling.h" 2  3/Declaration block 4 typedef Void (^billingresultcallback) (BOOL success, NSString *index,nsstrin g *message);  5  6 @interface cmgciapios:nsobject<gamebillingdelegate> 7 {8     gamebilling *_sdk; 9     nsstring *_ billingindex;10     billingresultcallback _callback;11}12 + (ID) sharedinstance;14-(void) Setdialogorientationmask: (Uiinterfaceorientationmask) orientationmask;16-(void) Dobillingwithuiandbillingindex :(NSString *) Billingindex                            isrepeated: (BOOL) isrepeated                               cpparam: (nsstring*) CPPARAM20                        Resultcallback: (billingresultcallback) callback;21 @end

It should be clear that there is no more explanation.

Here is the implementation file CMGCIAPIOS.M, as follows:

 1 #import "CMGCIAPiOS.h" 2 3 @implementation Cmgciapios 4 5 static Cmgciapios *_sharedinstance = nil;             6 7 + (ID) sharedinstance 8 {9 @synchronized (self) (_sharedinstance = = nil) 12 {13  _sharedinstance = [[Cmgciapios alloc] init];14}15}16 return _sharedinstance;17}18-(ID) init20 {(self = [super init])] {_sdk = [gamebilling initializegamebilling];24 _sdk.delegat E = self;25}26 return self;27}28-(void) Setdialogorientationmask: (uiinterfaceorientationmask) ORIENTATIONMASK3 0 {_sdk setdialogorientationmask:orientationmask];32}33-(void) Dobillingwithuiandbillingindex: (NSString *) bil Lingindex isrepeated: (BOOL) isrepeated Cpparam: (nsstring*)     CPPARAM37 resultcallback: (billingresultcallback) callback38 {(_callback! = nil) 41       {[_callback release];43  _callback = nil;44}45 _callback = [callback copy]; Note to copy47 [_SDK dobillingwithuiandbillingindex:billingindex isrepeated:isrepeat Ed cpparam:cpparam];51}52 #pragma mark-gamebillingdelegate54-(void) Onbillingre Sult: (billingresulttype) ResultCode55 billingindex: (NSString *) Index: (NSString *) mess age57 {+-BOOL b = (ResultCode = = Billingresulttype_paysuccess | | resultcode = = billingresulttype_paysuccess_activated         ); NSLog (@ "billing =%@%@%@", B? @ "Yes": @ "No", index, message); if (_callback! = Nil) 62 {63 _callback (b,index,message); 64 65//Call complete to release the [_callback release];67 _callback = nil;68} }70 @end

You can see that several of the methods mentioned have been encapsulated and have received callbacks.

Here is the C + + Bridge class section, the header file CMGCIAP.h:

1 #include <iostream> 2  3 class Cmgciap 4 {5 public:6     cmgciap (); 7     ~cmgciap (); 8      9 Public:10     s Tatic Cmgciap *sharedinstance (); one     bool init ();     void Setdobillingcallbackscripthandler ( int scripthandler); For Lua callback15     dobillingwithui (const char* billingindex,17                          bool isrepeated,18                          Const char* Cpparam);     private:21     int m_dobillingcallbackscripthandler;23     24};

Because of the reason for LUA binding with Cocos2d-x's Tolua tool, I put a separate approach to setting Lua callbacks, as follows:

1 void setdobillingcallbackscripthandler (int scripthandler);

It is better to put this scripthandler in the following function, so that the interface will be consistent with the objective.

1 void Dobillingwithui (const char* billingindex,2                      bool isrepeated,3                      const char* cpparam);

It doesn't matter, however, that setting LUA callback functions independently also has the advantage of being more flexible.

Note that the C + + Bridge class header file must remain "pure", do a purely C + + file, can not appear objective-c any code, otherwise it will destroy the above mentioned hierarchy.

Here is the implementation file CMGCIAP.MM:

 1 #include "CMGCIAP.h" 2 #include "cocos2d.h" 3 #include "script_support/ccscriptsupport.h" 4 5 #import "CMGCIAPiOS.h" 6 #import <Foundation/Foundation.h> 7 #import <UIKit/UIKit.h> 8 9 using_ns_cc;10 one static cmgciap* S_sharedin     Stance = null;12 Cmgciap::cmgciap () {M_dobillingcallbackscripthandler = 0;16}17 19 Cmgciap::~cmgciap () {20 }22 Cmgciap *cmgciap::sharedinstance () {if (s_sharedinstance = = NULL) + S_sharedinstanc     E = new Cmgciap ();}29 return s_sharedinstance;31}32//Init method encapsulates initialization of SDK Cmgciap::init () 35 {36 Because it is a vertical screen game, so here is directly set the PNS [[Cmgciapios sharedinstance] setdialogorientationmask:uiinterfaceorientationmaskportrait] , true;40}41 cmgciap::setdobillingcallbackscripthandler (int scripthandler), M_dobill                               Ingcallbackscripthandler = scripthandler;45}46 void Cmgciap::d obillingwithui (const char* billingindex,48 BOOL Isrepeated,49 Const char* cpparam) {nsstring *billingindexstring = [NSString str     ingwithutf8string:billingindex];53 nsstring *cpparamstring = [NSString stringwithutf8string:cpparam];55 56                                                      [[Cmgciapios Sharedinstance] dobillingwithuiandbillingindex:billingindexstring57                                                  Isrepeated:isrepeated58 cpparam:cpparamstring59 resultcallback:^ (BOOL success, NSString *index,nsstring *message) {60 6 1//through block will return results to Lua,objective-c to C + + Seamless connection:) Ccluastack *stack = ccluaengine::d efaultengine ()-&G T;getluastack (); Stack->clean (); Stack->pushboolean (success); Stack->pushstring ([In Dex utf8string]); stack->pushstring ([Message utf8string]); Stack->executefunctionbyhandler (M_dob IllingcallbackscripthandLer, 3); 69 70}];71} 

Well, the next step is to do LUA binding for C + + Bridge class, to generate the binding file, if binding with Tolua, the binding configuration file is as follows:

1 class Cmgciap 2 {3     static CMGCIAP *sharedinstance (); 4      5     void Setdobillingcallbackscripthandler (Lua_ FUNCTION Nhandler); 6      7     void Dobillingwithui (const char* Billingindex, 8                          bool isrepeated, 9                          const char* Cpparam); 10}

OK, here is the main coding work done, remember to do the appropriate location of the program LUA binding initialization work.

If all goes well, after the above work is done, the interface of the SDK can be called directly within Lua, and the next thing depends on you:)

Call ~ ~ ~

Article to this also almost, the whole idea and plan is these, if there is any place do not understand or do not understand, welcome message discussion:)

Thanks for watching!

Article Source: http://www.cnblogs.com/flyFreeZn/p/4152881.html

Cocos2d-x + Lua access iOS Native SDK implementation scheme [go]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.