Whoami
Whoami

Reputation: 14408

Unable to invoke function defined in Objective-C++ from Objective C

I tried the following program.

wc.h

int add(int, int);
int del (int, int);

wc.mm

int add(int x, int y)
{
    NSLog (@"Inside Wrapper Add");
}

int del( int x, int y)
{
   NSLog (@"Inside Wrapper Multiply");

}

In AppDelegate.m

1) Included wc.h

2) call add(20,30);

I see the compilation error 'Unknown Type Name 'NSString'.

what is My Understanding.

1) I am trying to Mix C++ and Objective C. That is, Invoking C++ from Objective C.

2) Found two ways to Achieve::

  1) Through Opaque Pointer ( PIMPL), Some how i achieve it through. 

  2) Using .mm ie: objective-C++ Source type which can be used to invoke pure C++.

What is my Question?

Having .mm [ Objective-C++] a function defined, why i am not able to invoke from Objective-C?

Kindly provide the input.

Upvotes: 1

Views: 142

Answers (1)

mah
mah

Reputation: 39797

You're unable to make the call from C to C++ (and the same principal applies when it's Objective) due to name mangling, something C++ does to your symbols to enable overloading.

If you declare extern "C" int add(int, int); for example, you declare that this C++ function needs to be callable by C and so no name mangling can occur (and no overloading can occur either).

Note that the C/ObjC side of things doesn't like the extern "C" notation, so your header files need to account for that (perhaps through an #ifdef __cplusplus).

Upvotes: 2

Related Questions