How to call a c library from unity3D C# code

1.5k views Asked by At

I'm new to unity3D and C# (and IOS :), but need to get things working with a legacy C library (.h & .a files) on iPhone. I've read some about Plugins from unity documentation, but still feel overwhelmed by the complicated procedures. Could any guru show me the correct way out of the mess? Thanks!

1

There are 1 answers

1
Nick On

Go through this link. This gives the idea for making plugins for iOS. If any doubt, ask.

A practical example for plugin

1) Make a C# file called AppControllerBinding.cs in the plugins folder in Unity and add the code as followed:

    using UnityEngine;
    using System.Collections;
    using System.Runtime.InteropServices;


    // All Objective-C exposed methods should be bound here
    public class AppControllerBinding
    {


    [DllImport("__Internal")]
    private static extern void _MyFunction(string myName);

    public static void MyFunction(string MyNameIN)
    {
            // Call plugin only when running on real device
          if( Application.platform == RuntimePlatform.IPhonePlayer )
             _MyFunction(MyNameIN);
    }

    }

2) Add the MyFunction() function to the bottom on the AppController.mm file inside Xcode as follows (after the @end statement):

extern "C"
{
    void _MyFunction(const char* MyName)
    {
        NSString* s = [NSString stringWithUTF8String: MyName];
        [Self logName:s]; //<-----logName is method which takes string parameter
        printf_console("_MyFunction() called in Appcontroller.mm in Xcode.\n");
    }
}

3) When you want to use the logName function of AppController.mm inside Unity just make a call like this:

AppControllerBinding.MyFunction("Nick");