Calling C Functions from Unity on Mac OS X/iOS

The Situation

At work I found myself needing to call previously written Objective-C code from Unity for an iOS app.  My options were to rewrite the code in C# or find a way to call the code from Unity.  I opted for not rewriting the code.

When looking around you’ll find ways to call C code from Unity on iOS apps using [DllImport(“__Internal”)]  This requires that when you build the app to device; the symbol you are referring is inside the executable somewhere.  Since on iOS dynamic libraries are verboten, this is your only option for iOS apps.  So just generate your xcodeproj, then edit it to link in your library that contains the C symbols you want to call from Unity.  This works but it will require that you build to device anytime you want to test your code that calls your C functions.  Unacceptable!  Especially since building to the iOS Simulator doesn’t work in my experience.

The other option is to make your library compile to a static library for iOS and a dynamic library for Mac OS X.  That way inside of the Unity editor we can load in the Mac OS X dynamic library to call the code without building to device, awesome!  There are a few gotchas though:

  • make sure your library is fat i386 and x86_64 (in my experience it only has to be i386 but I imagine this will change eventually)
  • you’ll need to have Unity Pro if you want to plop your library into the “Plugins” folder to have them magically distributed (if you are building for iOS this doesn’t matter anyways since you wont be distributing your dynamic library)
  • you’ll have to rename your library from “libfoo.dylib” to “foo.bundle”, the key part being the .bundle, it’s an error in the Mono runtime that they say will get fixed some day
  • if you aren’t using the Plugins directory you’ll have to put your library someplace where Mono can find it, like “~/lib”

The Code

The calling MonoBehaviour (NewBehaviourScript.cs):

The C code (foo.c):

The dylib Makefile:

shell command to put dylib in findable location:

 

References

 

Leave a Reply

Your email address will not be published. Required fields are marked *