Objective-C++ and NSInvocation (or IMP)
Objective-C++ and NSInvocation (or IMP)
- Subject: Objective-C++ and NSInvocation (or IMP)
- From: "E. Wing" <email@hidden>
- Date: Tue, 29 May 2007 20:53:44 -0700
This is somewhat of an academic exercise, though I do have a use for
this if I could get it to work in a general way. I'm wondering is
there a way to get NSInvocation or IMP to invoke method calls when the
methods have C++ objects in the arguments?
So for a trivial example:
@interface MyClassObjCpp : NSObject
{
}
- (std::string) appendString:(std::string)begining
withString:(std::string)ending;
@end
@implementation MyClassObjCpp
- (std::string) appendString:(std::string)begining
withString:(std::string)ending
{
return begining + ending;
}
@end
So the normal calling routines definitely work in Obj-C++:
MyClassObjCpp* myObject = [[MyClassObjCpp alloc] init];
std::string ret_string = [myObject appendString:std::string("Hello ")
withString:std::string("World")];
But when I try to use NSInvocation, I get a crash:
SEL mySelector = @selector(appendString: withString:);
NSMethodSignature* sig = [[myObject class]
instanceMethodSignatureForSelector:mySelector];
NSInvocation*myInvocation = [NSInvocation invocationWithMethodSignature:sig];
[myInvocation setTarget: myObject];
[myInvocation setSelector: mySelector];
// add 1st argument
std::string str1("Hello ");
[myInvocation setArgument:&str1 atIndex: 2];
// add 2nd argument
std::string str2("World");
[myInvocation setArgument:&str2 atIndex: 3];
std::string result;
[myInvocation retainArguments];
[myInvocation invoke];
unsigned int length = [[myInvocation methodSignature] methodReturnLength];
fprintf(stderr, "Length result is %d\n", length);
[myInvocation getReturnValue: &result];
NSLog(@"The result is: %s", result.c_str());
This crashes on the invoke call. I'm speculating it's because there
isn't good information about the size of the arguments, though maybe
it's something or I did something else wrong.
Strangely, if I try not passing C++ types as arguments (or no
arguments) but I still try to return a std::string, it actually works.
I get a return length of 4 though which I'm not sure sounds right. I'm
wondering if it's supposed to crash even though it seems to work.
I also tried using IMP directly i.e.
IMP myImp = [objPtr methodForSelector:@selector(appendString: withString:)];
myImp(objPtr,selPtr, ...);
but the va style parameter list definitely does not support C++ objects
(cannot pass objects of non-POD type through '...')
Since Obj-C++ can handle the conventional calling method, I was
wondering if there was a way to use a more generic calling convention
either through NSInvocation, IMP, or something else.
Thanks,
Eric
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden