iOS: define and use C++ in Objective-C++ - c++

Can anyone tell me on how to define and use BinaryWriter and BinaryReader (from OpenFrameworks project on GitHub) C++ classes in iOS 5.x -> Objective-C++ ?
what i do:
AppDelegate.h
#import <UIKit/UIKit.h>
#import "Poco/BinaryWriter.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>{
Poco::BinaryWriter *_myBinaryWriter;
}
#property (strong, nonatomic) UIWindow *window;
#end
AppDelegate.mm
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_myBinaryWriter = new Poco::BinaryWriter(NULL, NULL);
[self.window makeKeyAndVisible];
return YES;
}
#end
but in mm file i have compilation error:
No matching constructor for initialization of 'Poco::BinaryWriter'
What is wrong and whar to do?
p.s. path to Headers of OpenFrameworks is configured in setting of project and linker can see Poco classes.
Thanks you.

You just have to set your .m to .mm and then you can use c++.
So, from
class.h
class.m
to
class.h
class.mm
This line
_myBinaryWriter = new Poco::BinaryWriter(NULL, NULL);
creates your poco::binarywriter. The error
No matching constructor for initialization of 'Poco::BinaryWriter'
Says that you are not creating it correctly.
You have to properly create it following these guidelines:
BinaryWriter(std::ostream& ostr, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER);
/// Creates the BinaryWriter.
BinaryWriter(std::ostream& ostr, TextEncoding& encoding, StreamByteOrder byteOrder = NATIVE_BYTE_ORDER);
/// Creates the BinaryWriter using the given TextEncoding.
///
/// Strings will be converted from the currently set global encoding
/// (see Poco::TextEncoding::global()) to the specified encoding.

Poco::BinaryWriter(NULL, NULL) there are no constructors with that signature in BinaryWriter.h, and you cannot convert from NULL to std::ostream&.
To test the BinaryWriter with the standard output (std::cout):
#import "AppDelegate.h"
#include <iostream>
#implementation AppDelegate
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Only for testing
_myBinaryWriter = new Poco::BinaryWriter(std::cout);
(*_myBinaryWriter) << 1 << 3.14f;
[self.window makeKeyAndVisible];
return YES;
}
#end
Once you confirm that this is indeed working you can move on to actually using other std::ostream derived classes such as std::ofstream (output file stream).

This is not an answer to your specific question but general advice.
With more recent versions of the LLVM compiler (i.e. Xcode 4.x) you can put your instance variables in the implementation, not the interface. i.e.
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#end
#implementation AppDelegate
{
Poco::BinaryWriter *_myBinaryWriter;
}
// etc
#end
This means that your instance variables are now hidden from files that import the header and the header now contains no C++ code so you can import it into other Objective-C files without making them Objective-C++

Related

EXC_BAD_ACCESS Xcode from my c++ wrapper in objective-c++ and swift bridging header

I'm working on a app using openCV and a utility class "Detector" created in C++. I want to create a objective-c++ wrapper "DetectorWrapper" for the c++ class and use this wrapper in Swift (bridging header). But know when I try to call a fonction from DetectorWrapper, my app crash with the error : EXC_BAD_ACCESS
I read sowewhere that to be allow to use the objective-c++ class in Swift, I cannot include c++ file in the DetectorWrapper.h so I use the type id.
Here is my c++ class: "Detector.h"
#include "opencv2/opencv.hpp"
class Detector
{
public:
// Constructor
Detector(int inputPlayerIdx);
// Scan the input video frame
void scanFrame(cv::Mat frame);
// Tracking API
bool isTracking();
};
My wrapper: "DetectorWrapper.h"
#interface DetectorWrapper : NSObject
#end
#interface DetectorWrapper ()
#property (nonatomic, readwrite, assign) id bld;
- (id)init: (int) inputPlayerIdx;
- (void)dealloc;
- (void) scanFrame: (UIImage*) frame;
- (bool) isTracking;
#end
"DetectorWrapper.mm"
#import "DetectorWrapper.h"
#import "Detector.hpp"
#import "UIImage+OpenCV.h"
#implementation DetectorWrapper
#synthesize bld = _bld;
- (id)init: (int) inputPlayerIdx {
self = [super init];
if (self) {
_bld = (__bridge id) new Detector(inputPlayerIdx);
}
return self;
}
- (void)dealloc {
//[self->_bld dealloc];
//[super dealloc];
//delete _bld;
}
- (void) scanFrame: (UIImage*) frame{
[self->_bld scanFrame:frame];
}
- (bool) isTracking{
return [self->_bld isTracking];
}
#end
Using this in Swift:
let detector = DetectorWrapper(2)
detector.isTracking()
with the file "Detector.h" in Bridging Header.
I got the "EXC_BAD_ACCESS" error when calling for .isTracking
I don't understand the problem at all and how to figure it out.
Maybe I just made a mistake coding my objective-c++ wrapper, I'm not used to this language. Any ideas?
One problem here is that a C++ object is used as if it was an Objective-C object, and these kinds of objects are not interchangeable.
For illustration purposes and for simplicity, let's eliminate the scanFrame method. Then DetectorWrapper.h becomes
#interface DetectorWrapper : NSObject
- (id)init: (int) inputPlayerIdx;
- (void)dealloc;
- (bool) isTracking;
#end
and the wrapper implementation:
#implementation DetectorWrapper
{
// Instance variable to hold a C++ object pointer
Detector * ptrDetector;
}
- (id)init: (int) inputPlayerIdx {
self = [super init];
if (self) {
ptrDetector = new Detector(inputPlayerIdx);
}
return self;
}
- (void)dealloc {
// Don't want to leak the C++ Detector instance
delete ptrDetector;
}
- (bool) isTracking{
return ptrDetector->isTracking();
}
#end
Please note that when you re-introduce scanFrame, you won't be able to just pass UIImage* to ptrDetector->scanFrame(), which takes cv::Mat, you'll have to do some magic in your wrapper's scanFrame to convert between the 2 types, but that's a topic in its own right, I think. BTW, I'm assuming that in your example Detector.h and Detector.hpp refer to the same file, it's just a typo.

Objective-C - Creating a wrapper file for C++ functions?

I'm going to write a lot of C++ functions for my Objective-C code (due to third-party functions). And I was thinking it may be a good idea to abstract out the C++ code by having a intermediate Objective-C++ file wrapper between the Objective-C code and the C++ code. The layout as I have it currently is the ViewController.m file creates an instance of my wrapper Objective-C++ class. This class calls it's instance methods which in turn call the C++ code. A simple version of this is given below. Is this a bad way to do this? Is there a more appropriate way to approach this? Any other criticisms with the code as is? Thank you much!
ViewController.m
#import "ViewController.h"
#import "CppWrapper.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CppWrapper *wrap = [[CppWrapper alloc] init];
double n = 5;
n = [wrap cppTimesTwo:n];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
CppWrapper.mm
#import "CppWrapper.h"
#import "Cpp.h"
#implementation CppWrapper
- (double)cppTimesTwo:(double) number
{
return timesTwo(number);
}
#end
Cpp.cpp
#include "Cpp.h"
double timesTwo(double number)
{
return 2 * number;
}
We did the same thing in a project to reuse some C source code and it worked very well. I think it is a good way to do this.

Calling C++ from Objective-C

For those of you who have successfully been able to call C++ code from Objective-C, will you please enlighten me?
This link says you need to wrap your C++ code using a technique he describes in his article. It looks good but I still have problems.
This link says that as long as the Objective-C class calling the C++ class has been converted to a .mm (Objective-C++) class then the two should work nicely together.
Each of these approaches are causing me grief the minute I try to add a method call. Can somebody please give me code for a simple Hello World iOS app that uses Objective-C for the "Hello" part and a C++ class for the "World" part with an Objective-C++ class in the middle? Or do I still have the entire concept wrong?
Essentially you need an ObjC class with .mm extension that calls an ObjC class with .mm extension. The second one will be used as a C++ wrapper class. The wrapper class will call your actual .cpp class. It's a little tricky, so I'm going to give you some verbose code. Here is an overview of the project:
In your ObjC code (ViewController) you would call the CplusplusMMClass
- (IBAction)buttonPushed:(UIButton *)sender {
self.mmclass = [[CplusplusMMClass alloc]init]; // bad practice; but showing code
NSString *str = [self.mmclass fetchStringFromCplusplus];
[self populateLabel:str];
}
Here is the CplusplusMMClass .h and .mm
#import <Foundation/Foundation.h>
#import "WrapperClass.h"
#interface CplusplusMMClass : NSObject
#end
#interface CplusplusMMClass()
#property (nonatomic, strong) WrapperClass *wrapper;
- (NSString*)fetchStringFromCplusplus;
#end
#import "CplusplusMMClass.h"
#import "WrapperClass.h"
#implementation CplusplusMMClass
- (NSString*)fetchStringFromCplusplus {
self.wrapper = [[WrapperClass alloc] init];
NSString * result = [self.wrapper getHelloString];
return result;
}
#end
Here is WrapperClass .h and .mm
#ifndef HEADERFILE_H
#define HEADERFILE_H
#import <Foundation/Foundation.h>
#if __cplusplus
#include "PureCplusplusClass.h"
#interface WrapperClass : NSObject
#end
#interface WrapperClass ()
- (NSString *)getHelloString;
#end
#endif
#endif
#import "WrapperClass.h"
#include "WrapperClass.h"
#include "PureCplusplusClass.h"
using namespace test;
#interface WrapperClass ()
#property (nonatomic) HelloTest helloTest;
#end
#implementation WrapperClass
- (NSString *)getHelloString {
self.helloTest = *(new HelloTest);
std::string str = self.helloTest.getHelloString();
NSString* result = [[NSString alloc] initWithUTF8String:str.c_str()];
return result;
}
#end
Here is the PureCplusplusClass .h and .cpp
#ifndef __HelloWorld__PureCplusplusClass__
#define __HelloWorld__PureCplusplusClass__
#include <stdio.h>
#include <string>
using namespace std;
namespace test {
class HelloTest
{
public:
std::string getHelloString();
};
}
#endif /* defined(__HelloWorld__PureCplusplusClass__) */
#include <stdio.h>
#include <string>
std::string test::HelloTest::getHelloString() {
std::string outString = "Hello World";
return outString;
}
This code is not perfect! I'm having trouble with the namespace test being recognized. I'll update when I can.
But this should get you there!!!!
Another (contrived) one:
Use a C++ class as an ivar:
File Foo.h
#import <Foundation/Foundation.h>
#interface Foo : NSObject
#property (nonatomic, readonly) NSString* what;
#end
File: Foo.mm
#import "Foo.h"
#include <string>
#implementation Foo {
std::string _string; // C++ class must have a default c-tor
}
- (id)init
{
self = [super init];
if (self) {
_string = "Hello, World!"
}
return self;
}
- (NSString*) what {
NSString* result = [[NSString alloc] initWithBytes:_string.data()
length:_string.size()
encoding:NSUTF8StringEncoding];
return result;
}
#end
Note:
An executable may need to explicitly link against the C++ library, e.g. by adding an additional flag to "Other Linker Flags": -lc++
Alternatively, the main.m file can be renamed to main.mm.
The latter is more robust in selecting the "correct" library, since the tool chain will do that itself. But perhaps, for anyone else examining the project, a renamed "main.m" may not be that obvious and may cause confusion.
I ran into this situation with xcode 12.4, needing to use an existing C++ class "CppModule" in an objective-c project. Here is what I did.
First problem was that #include in CppModule.hpp gave a compiler error: 'string' file not found. Fixed that by wrapping the .hpp file contents in
#if defined __cplusplus
declarations
#endif
Then string var declarations gave another compiler error: Unknown type name 'string'; did you mean 'std::string'? Fixed that by:
#include <string>
using namespace std;
The C++ CppModule.cpp, the CppModule.hpp include file, the calling objective-c module.m, and it's module.h files MUST all be set as Type "Objective-C++ Source", using xcode's Inspector (top right in the editor window). Renaming module.m to module.mm also sets the type to "Objective-C++ Source" (xcode 12.4). Perhaps good to use .mm, as a reminder it calls C++.
In the module.h file include the C++ header:
#include < CppModule.hpp>
Odd (to me) is that in the module.h file "CppModule" is not recognised as a known type, so you cannot declare vars or properties of that type in your module.h, but in the module.m(m) file it is a known type. In the module.mm file, after the #implementation add:
static CppModule *module_cpp;
Now you can, e.g. in the module.mm's init, call the C++ module's initialiser, like:
module_cpp = new CppModule(parameters);
And the C++ module remains accessible via that static module_cpp *pointer.
Call the module.cpp's methods (example) in your objective-c method:
CppModule::Result r = module_cpp->CppMethod();
Appears to work absolutely fine!
If anyone can explain the oddities in 4. I'd be grateful.
The module I needed just does some complex (numeric) calculations, and I did not feel like converting that code to Objective-C.
IOS Netbanking sample for Objective c
- (IBAction)Button:(id)sender {
NSMutableArray *userdata=[[NSMutableArray alloc]initWithObjects:#"Name",#"CreditcardNumber",#"Pinnumber",#"Active", nil]; // arrkey = userdata.
NSMutableArray *Yogesh=[[NSMutableArray alloc]initWithObjects:#"Yogesh",#"908380637367",#"5656",#"yes", nil];
NSMutableArray *sabari=[[NSMutableArray alloc]initWithObjects:#"Sabari",#"7635298721",#"6543",#"no",nil];
NSMutableArray *rajesh=[[NSMutableArray alloc]initWithObjects:#"rajesh",#"8373197272",#"8765",#"yes",nil];
NSMutableArray *Ramya =[[NSMutableArray alloc]initWithObjects:#"Ramya ",#"123456",#"9898",#"No",nil];
NSMutableDictionary * dic= [[NSMutableDictionary alloc]initWithObjects:Yogesh forKeys:userdata];
NSMutableDictionary * dic1=[[NSMutableDictionary alloc]initWithObjects:sabari forKeys:userdata];
NSMutableDictionary * dic2=[[NSMutableDictionary alloc]initWithObjects:rajesh forKeys:userdata];
NSMutableDictionary * dic3=[[NSMutableDictionary alloc]initWithObjects:Ramya forKeys:userdata];
/* NSLog(#"%#", dic);
NSLog(#"%#", dic1);
NSLog(#"%#", dic2);*/
NSMutableArray * arraylist=[[NSMutableArray alloc]initWithObjects:dic,dic1,dic2,dic3, nil];
NSLog(#"Array = %#", arraylist);
NSLog(#"user entered value %d", _ccNumber.text.intValue);
NSLog(#"pin number %d ",_pin.text.intValue);
for(int i = 0; i< [arraylist count]; i++){
NSMutableDictionary *dictionary= arraylist[i];
// NSLog(#"userdata is [%d] %#",i,[dictionary objectForKey:#"Pinnumber"]);
NSInteger a;
NSInteger vx;
NSString *b;
NSString *str;
a = (self.ccNumber.text.integerValue);
vx = (self.pin.text.integerValue);
b = ([dictionary objectForKey:#"CreditcardNumber"]);
str = ([dictionary objectForKey:#"Pinnumber"]);
NSInteger c = [b integerValue];
NSInteger d = [str integerValue];
if(a == c && vx == d){
NSLog(#" user data is [%d] Name: %#",i,[dictionary objectForKey:#"Name"]);
NSLog(#" user data is [%d] Card Number: %#",i,[dictionary objectForKey:#"CreditcardNumber"]);
NSLog(#" user data is [%d] Pin Number :%#",i,[dictionary objectForKey:#"Pinnumber"]);
NSLog(#" user data is [%d] Active: %#",i,[dictionary objectForKey:#"Active"]);
}else{
NSString *DataStatus= #"Invalid Card Number";
self.dataStatusLbl.text = DataStatus;
NSLog(#"%#",DataStatus);
}
}
}
#end

Image processing in iOS + C++ in iphone app

My first question is that if I write a class in C++ using opencv library to detect any object in an image and call that c++ class in objective-C (xcode project) then will this technique work?
and
Second question is that how I can add c/c++ class in my iphone app project and use it in my traditional ViewController Class.
What I have done till now is uder
: Created a TabView Application with one ViewController.
: Added a Push Button in that ViewController.
: Added a File.c class which is just printing string.
: Imported "File.c" in my ViewController.h and ViewController.m class like
MY ViewController.h class
#import <UIkit/UIkit.h>
#import "file.c"
MY ViewController.m class
#import "FirstViewController.h"
#import "File.c"
now on action of the push button I want to call that C class that I have already added in the project.
I am hoping to get good and beneficial answers.
Regards
File.c
#ifndef testC_File_c
#define testC_File_c
#include <stdio.h>
void say_hello() {
printf("Hello World!");
}
#endif
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
- (IBAction) buttonDown:(id)sender;
#end
ViewController.mm
#import "ViewController.h"
#include "File.c"
#interface ViewController ()
#end
#implementation ViewController
- (IBAction) buttonDown:(id)sender
{
say_hello();
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end

Can't find standard C++ includes when using C++ class in Cocoa project

I have a Cocoa project (a Mac OS X app), all Objective-C. I pulled in one C++ class (which I know works) from another project, and make an Objective-C wrapper for it. The ObjC wrapper class is using a .mm extension. However, the C++ header file contains #includes to standard C++ header files (<vector>, for example), and I get errors on those.
A minimal example would look like the following. CppClass is the C++ class, and CppWrapper is the ObjC class which wraps it.
// CppClass.h
#ifndef _CPP_CLASS_H_
#define _CPP_CLASS_H_
#include <vector>
class CppClass
{
public:
CppClass() {}
~CppClass() {}
private:
std::vector<int> my_ints;
};
#endif /* _CPP_CLASS_H_ */
// CppWrapper.h
#import <Foundation/Foundation.h>
#import "CppClass.h"
#interface CppWrapper : NSObject {
CppClass* myCppClass;
}
#end
// CppWrapper.mm
#import "CppWrapper.h"
#implementation CppWrapper
- (id)init
{
self = [super init];
if (self) {
myCppClass = new CppClass;
}
return self;
}
- (void)dealloc
{
delete myCppClass;
[super dealloc];
}
#end
// The file that uses CppWrapper
// TestAppDelegate.m
#import "TestAppDelegate.h"
#import "CppWrapper.h"
#implementation TestAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
myWrapper = [[CppWrapper alloc] init];
}
#end
The error I'm getting is the #include of vector in CppClass.h. The error is
lexical or Preprocessor issue: 'vector' file not found
This code works fine in another (all C++) project, so I'm pretty sure it's a build setting, or something I've done wrong in the wrapper class. I'm using Xcode 4. I created a default Cocoa Mac OS app project and all settings are default.
Update: I just realized that if I set TestAppDelegate's File Type to Objective-C++ (or rename it to TestAppDelegate.mm), it works. What I don't understand is, this class is pure Objective-C; why does it have to be compiled as Objective-C++? The whole point of having an Objective-C wrapper on my C++ class is so that I don't have to build the entire project as Objective-C++.
The problem with your CppWrapper class is that it doesn't present a pure Objective-C interface. In your CppWrapper.h file, you're importing the C++ class's header file, which means that any Objective-C class that imports the wrapper class will need to be compiled as Objective-C++, including your TestAppDelegate.
Instead, you'd need to do something like this to completely hide the C++ within the CppWrapper.mm file:
// CppWrapper.h
#import <Foundation/Foundation.h>
#interface CppWrapper : NSObject {
void *myCppClass;
}
- (void)doSomethingWithCppClass;
#end
// CppWrapper.mm
#import "CppWrapper.h"
#import "CppClass.h"
#implementation CppWrapper
- (id)init {
self = [super init];
if (self) {
myCppClass = new CppClass;
}
return self;
}
- (void)dealloc {
delete myCppClass;
[super dealloc];
}
- (void)doSomethingWithCppClass {
static_cast<CppClass *>(myCppClass)->DoSomething();
}
#end
Personally, I would
#include "CppClass.h"
instead of importing it.
That's probably not your problem though.