a method of call obj-c function in *.cpp file

When I use cocos2d-x, the excellent platform, but some troubles make me
perplexed, one of those is how could I call obj-c function in cpp file. for
example: you may call obj-c functions when you want to execute ios
inner-purchase functions.

you know that we could compile obj-c, c++ and c code in .mm file, but
we can not compile obj-c code in
.cpp file.

fortunately we could call some functions in .cpp file which declared by cpp
or c, but implemented by
.mm file

so we just need to make a wrapper file, I call that: bridge file.

sample:
we build some files follow:
objectivec.h // pure objective-c code
objectivec.mm // pure objective-c code
bridge.h // pure c or cpp code, called by **.cpp file
bridge.mm // mixed code, c, cpp or objective-c
cpp.h // pure c or cpp code
cpp.cpp // pure c or cpp code
/////////////////////////////////////////////////////////////////
objectivec.h
`interface ObjectiveC : NSObject {

}

// buy a product, make a inner-purchase request
-(void) buyProduct:(int)productid;
`end

/////////////////////////////////////////////////////////////////
objectivec.mm
`implementation ObjectiveC

-(void) buyProduct:(int)productid
{
    // send a inner-purchase request
    // we just print a log here simplely
    NSLog( `“send inner-purchase request” );

}
@end
////////////////////////////////////////////////////////////////
bridge.h
// function declared by c
void callObjectiveC;
////////////////////////////////////////////////////////////////
bridge.mm
//function implements by objective-c
void callObjectiveC
void callObjectiveC
{
// call objetive-c function
ObjectiveC** pobj = [[ObjectiveC alloc] init];
[pobj buyProduct: v];
[pobj dealloc];
}

////////////////////////////////////////////////////////////////
cpp.h
class Cpp
{
public:
void callObjectiveC( int v );
};

////////////////////////////////////////////////////////////////
cpp.cpp
#include “bridge.h” //look at here
void Cpp::callObjectiveC( int v )
{
buyProduct( v ); //this function in bridge.h declared by c implements by objective-c
}

1 Like

Hi Pengfei,

That is exactly what I was looking for but I got problems when I was integrating it in my game.
Can you put a link with a sample project? :slight_smile:

Thank you in advance.

roger solsona wrote:

Hi Pengfei,
>
That is exactly what I was looking for but I got problems when I was integrating it in my game.
Can you put a link with a sample project? :slight_smile:
>
Thank you in advance.

:slight_smile: sorry, there is no sample project, I will make one if I am in spare.