一. 用戶手冊
Building an Application with a Native Plugin for iOS
為iOS創(chuàng)建一個帶有本地插件的應用程序
用戶手冊里給出了一種簡單的C#調用iOS C++本地插件的方式,概括步驟如下:
- C#腳本中聲明外部函數(shù)并調用
- 導出Xcode工程
- Xcode工程中新建.mm或者.cpp文件,實現(xiàn)函數(shù)
二. 示例
一個簡單的例子:界面上有一個button,每點擊一次汗洒,button上的數(shù)字+1
- Unity3D C#腳本中聲明外部函數(shù)Add
using System.Runtime.InteropServices;
[DllImport ("__Internal")]
private static extern int Add(int x); //返回x+1
- C#調用Add,并修改button上的text.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;
public class ButtonControl : MonoBehaviour {
public Text text;
int cnt = 0;
[DllImport ("__Internal")]
private static extern int Add(int x);
public void ButtonClick(){
cnt = Add (cnt);
text.text = "" + cnt;
}
}
-
導出Xcode工程父款,新建.mm(或.cpp)文件
匯編后的C#代碼和C++代碼是在link階段被鏈接到一起的溢谤。C++代碼不需要.h頭文件。
代碼要放在Classes
目錄下憨攒。修改Unity項目世杀,以append
方式導出、更新Xcode工程時肝集,該文件夾不會被覆蓋瞻坝。
編寫Add.mm,C++實現(xiàn)函數(shù)
提供給C#調用的C++接口需加上extern "c"
(按C語言進行編譯)杏瞻,否則會link失敗所刀。
extern "C"{
int Add(int x){
return x+1;
}
};
- build工程,下載測試
三. 參數(shù)傳遞
關于C#和C++數(shù)據(jù)類型的對應關系我也沒有仔細研究過捞挥,不過網(wǎng)上資料應該挺多的浮创。
我自己用到的有int
、double
砌函、float
斩披,這幾個基礎類型C#和C++是一樣的。
數(shù)組類型參數(shù)傳遞方式:
C#聲明與調用
[DllImport("__Internal")]
private static extern bool PF(double[] p);
double[] params = new double[6];
if (!PF (params)) {
};
C++實現(xiàn)
bool PF(double* params){
//……
return true;
}