Skip to content

Instantly share code, notes, and snippets.

@sjmulder
Last active April 29, 2022 17:32
Show Gist options
  • Save sjmulder/6306595 to your computer and use it in GitHub Desktop.
Save sjmulder/6306595 to your computer and use it in GitHub Desktop.
Sample code for a hypothetical Objective-C++/CLI language.
#include <iostream>
#include <msclr/marshal.h>
#include <msclr/marshal_cppstd.h>
#import <Foundation/Foundation.h>
// Sample code for a hypothetical Objective-C++/CLI language
ref class ClrClass;
@class ObjCClass;
class CppClass {
void hello_from(std::string sender);
void greet(ObjCClass *target);
void greet(ClrClass ^target);
};
ref class ClrClass {
void HelloFrom(System::String ^sender);
void Greet(CppClass &target);
void Greet(ObjCClass *target);
};
@interface ObjCClass : NSObject
- (void)helloFrom:(NSString *)sender;
- (void)greetCPP:(CppClass &)target;
- (void)greetCLR:(ClrClass ^)target;
@end
// C++ class implementation
void CppClass::hello_from(std::string sender)
{
std::cout << "C++ greeted by " << sender << std::endl;
}
void CppClass::greet(ObjCClass *target)
{
std::string sender = "C++";
NSString *nsstr = [NSString stringWithUTF8String:sender.c_str()];
[target helloFrom:nsstr];
}
void CppClass::greet(ClrClass ^target)
{
std::string sender = "C++";
System::String ^clrstr = marshal_as<System::String^>(sender);
target.HelloFrom(clrstr);
}
// C++/CLI class implementation
void ClrClass::HelloFrom(System::String ^sender)
{
System::Console::WriteLine("C++/CLI greeted by {0}", sender);
}
void ClrClass::Greet(CppClass &target)
{
System::String ^sender = "C++/CLI";
std::string stdstr = marshal_as<std::string>(sender);
target.hello_from(stdstr);
}
void ClrClass::Greet(ObjCClass *target)
{
System::String ^sender = "C++/CLI";
std::string stdstr = marshal_as<std::string>(sender);
NSString *nsstr = [NSString stringWithUTF8String:stdstr.c_str()];
[target helloFrom:nsstr];
}
// Objective-C class implementation
@implementation ObjCClass
- (void)helloFrom:(NSString *)sender
{
NSLog(@"Objective-C greeted by %@", sender);
}
- (void)greetCPP:(CppClass &)target
{
NSString *sender = @"Objective-C";
std::string stdstr = [sender UTF8String];
target.hello_from(stdstr);
}
- (void)greetCLR:(ClrClass ^)target
{
NSString *sender = @"Objective-C";
System::String ^clrstr = marshal_as<std::string>(sender);
target.HelloFrom(clrstr);
}
@end
int main(int argc, const char *argv[])
{
CppClass cpp;
ClrClass ^clr = gcnew ClrClass();
ObjCClass *objc = [ObjCClass new];
cpp.greet(clr);
cpp.greet(objc);
clr.Greet(cpp);
clr.Greet(objc);
[objc greetCPP:cpp];
[objc greetCLR:clr];
return 0;
}
@MarkusSecundus
Copy link

This would be insane. How come it doesn't exist? Such pity xxD.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment