tags:

views:

329

answers:

3

Hi, I have to call an objective C method from a cpp Function.

I have a class C, whose object address is required in this function. I did come across another link which guided me on how to have a reference to the class C, and use it for invocation from the cpp function.

In my case, there is one small difference in that the Class C is already instantiated, and I would not want to allocate an object again. So how can I get its object address?

The code looks like this:

C.h

import Cocoa/Cocoa.h

id refToC

@interface C: NSObject
{

;

somemethod;

;
}

@end

C.m

@implementation C

- (void) somemethod
{
;
;
}

@end

B.mm

import C.h

void func()
{

//I need the address of object here, so as to invoke:
[refToC somemethod];
}

Thanks in Advance

~ps7

+3  A: 

The id type is already a pointer to an object. Once you have created a valid object, e.g.:

refToC = [[C alloc] init]
Matt Kane
On debugging, I found that it points to NULL.
ps7
In func(), do you have a valid object? (see edit)
Matt Kane
A: 

The easiest way is to make use of the singleton design pattern. Here's a common way to make use of that pattern in Objective-C:

Widget.h

@interface Widget : NSObject {
    // ...
}

// ...

- (void)someMethod;
+ (Widget *)sharedWidget;

@end

Widget.m

@implementation Widget

// ...

+ (Widget *)sharedWidget {
    static Widget *instance;

    @synchronized (self) {
        if (!instance)
           instance = [[Widget alloc] init];
    }

    return instance;
}

@end

CppWrapper.mm

void methodWrapper() {
    [[Widget sharedWidget] someMethod];
}
John Calsbeek
A: 

Thanks a lot for your pointers. I had missed telling that the class C is a controller class. I tried assigning refToC to self in awakeFromNib, and the invocation in func() worked like a charm.

Thanks Matt and John for your pointers.

~ ps7

ps7