Search code examples
objective-cmacosobjective-c++objective-c-runtimedistributed-objects

Objective-C++: Is there any way to vend a C++ object?


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++.