Objective-C++: Is there any way to vend a C++ object?
-
22-06-2021 - |
Question
I am making heavy use of Objective-C++. I know that while I can include C++ code in my Objective-C code, the converse is not true. I'd like to vend a custom C++ object I have created, to my Objective-C process through a distributed object. When I try to do this, I get the following error message:
error: cannot convert ‘custom_class*’ to ‘objc_object*’ in argument passing
Is there any way to vend a custom C++ object, to another Objective-C process?
The code I have:
#import <Cocoa/Cocoa.h>
#import <iostream>
#import <stdio.h>
using namespace std;
class custom_class {
public:
custom_class();
~custom_class();
void hello();
};
custom_class::custom_class() { }
custom_class::~custom_class() { }
void custom_class::hello() { cout << "Hello World!" << endl; }
int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
cout << "Starting vendor " << endl;
custom_class *test = new custom_class();
NSConnection *connection = [NSConnection connectionWithReceivePort:[NSPort port] sendPort:nil];
[connection setRequestTimeout:1];
[connection setRootObject:test];
[connection registerName:@"DisObjTest"];
[[NSRunLoop currentRunLoop] run];
[pool drain];
return 0;
}
Solution
This cannot be done without wrapping the C++ class in an Objective-C class. All the runtime machinery that makes distributed objects possible is not available in C++.
OTHER TIPS
Wrap it inside a objective-C interface:
class custom_class;
@interface custom_class_wrapper : NSObject
@propery (nonatomic, assign) custom_class* obj;
@end
Or inside an NSValue
, this requires casts though
custom_class a;
id obj = [NSValue valueWithPointer:&a];
custom_class* a_val = static_cast<custom_class*>([obj pointerValue]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow