top of page

External code to call native Object-C codes in iOS

  • Ugo Odukwe
  • Jun 15, 2015
  • 2 min read

In this exercise, we're going to see how we can use external code to call Native iOS functions. For example, we can call functions to bring up popups and access frameworks such as iCloud, Health kit and Store kit.

The external program we'll be using is Unity 3D SDK. I will be coding in C#.

We start by creating a C# file in Unity and name it CSharpToObjC, Unity automatically builds a class within the file with a class named CSharpToObjC. In the file, we shall import InterlopServices and declare our functions. For test purposes, we shall include this call in a preprocessor scope. The preprocessor shall be set for only when the code is running on an iOS device.

#if (UNITY_IOS && !UNITY_EDITOR)

using System.Runtime.InteropServices;

For this example, we'll be activating our store. It is necessary to activate a store before we can call any of the functions or services that the Store framework offers. For example, before attempting to restore purchases a user might have made in the past, the Store must be activated.

Then inside the CSharpToObjC class, we shall add this preprocessor:

public class CSharpToObjC

{

#if (UNITY_IOS && !UNITY_EDITOR)

[DllImport ("__Internal")]

private static extern void _ActivateStoreProducts( string Prod);

// Then you may create a method that calls the above prototype

void callActivateStore( string Prods)

{

_ActivateStoreProducts( Prods);

}

}

Now, create a header file (.h) and place it anywhere in your Unity Xcode build directory

This is written in Objective-C

@interface StoreInterface : NSObject <SKProductsRequestDelegate, SKRequestDelegate>

{

// Some declared variables

}

+ (StoreInterface *) instance;

- (void) activStore;

Also, create an Objective C file (.mm) and place it anywhere in your Unity Xcode build directory.

- (void)activStore

{

SKProductsRequest *request;

request.delegate = self;

[request start];

}

extern "c"

{

void _ActivateStoreProducts (char * products)

{

// Some code with char* products.

[[StoreInterface instance] activStore];

}

}

In conclusion. We can use C# in an external application such as Unity to communicate to Xcode and use Objective C to call native iOS (or OSX) functions. Not only Objective-C but C and C++ maybe used as well. The process is to use interlop services to call [DllImport ("__Internal")], then decalare the prototype of the function that shall be placed in a .mm file. In the .mm file, you may now complete the body of the function and wrap it using extern C. The body of the function is totally open to calling any Xcode services

 
 
 

Comments


Featured Posts
Recent Posts
Archive
Search By Tags
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square

© 2020 by UGO ODUKWE. 

bottom of page