Getting a basic native plugin working

Hi all

I’ve written a small bit of obj-c that returns the peak frequency of audio going through the iphone mic. I’d like to integrate it into my unity project, so I’ve started by reading the plugins tutorial, and trying to get this:

extern "C" {
float _PassFreq () { return 5.0F; }
}

To be called by:

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

public class PeakFreqImport : MonoBehaviour {
	
	static int freq = 0;
	//static int pfreq;
	
	/* Interface to native implementation */

	[DllImport ("__Internal")]
	private static extern int _PassFreq ();
	
	public static int GetFrequency ()
	{
		// Call plugin only when running on real device
		if (Application.platform != RuntimePlatform.OSXEditor) {
			freq = _PassFreq();
			return freq;
		}
		return freq;
	}

And attached to a cube GameObject:

private var centerx = Screen.width / 2;
private var centery = Screen.height / 2;

private var labelStyle : GUIStyle = new GUIStyle();
private var freqString = 0;
private var pfreq;

function Start () 
{
	labelStyle.alignment = TextAnchor.MiddleCenter;
	labelStyle.normal.textColor = Color.white;
	labelStyle.fontSize = 24;
}

function OnGUI () 
{
	GUI.Label(new Rect(100, 25, 100, 25), freqString.ToString(), labelStyle);
}

// Update is called once per frame
function Update () {
	freqString = PeakFreqImport.GetFrequency();	
	//Debug.Log(freqString);
}

I read the Bonjour iphone native code example from the Unity site…and based my code on it. But, it’s not working. If I try to build the xcode project from Unity 3.0, with player settings setup, and targetting iOS 3.2, I get:

Going into play mode works, and I get 0 on the screen, which is coming from the ‘return freq;’ outside the RuntimePlatform check…if I change that to ‘return _PassFreq();’ , MonoDevelop shows:

Which I can only assume means it can’t find the function…but why? Because it won’t even go that far unless running on the device itself?

Not sure how to solve this…help?!

David Plans

Just to update…thanks to azupko on #unity3d irc, who pointed out I was using int in c# and float in obj-c, I now get to xcode compilation, but trying to compile the project gives:

Which is exactly what I got when trying to call functions from the finished pitch tracker I’ve got…

Anyone? I must be missing something basic about native calls?

David Plans

For reference, the .m containing the native function had to be renamed to .mm

Also, copying the .mm file into the Classes folder after building the xcode project and BEFORE hitting build in xcode helps a lot