动态加载dll
static string passStr = "Dxl";
static string targetPath = "Assets/Resources/DllTest/TestDll.bytes";
static string dllPath = "Assets/Plugins/Test2019Dll.dll";
//将一个正常的dll变成一个加密的dll
static void CreateBinaryDll(string dllPath)
{
//读取原始数据
var fileStream = new FileStream(dllPath, FileMode.Open);
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
if(File.Exists(targetPath))
{
File.Delete(targetPath);
}
FileStream fs = new FileStream(targetPath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
//加密位
byte[] passTemp = System.Text.Encoding.UTF8.GetBytes(passStr);
//保存加密后的数据
byte[] temps = new byte[bytes.Length + passStr.Length];
//先写入加密数据
for (int i = 0; i < passTemp.Length; ++i)
{
temps[i] = passTemp[i];
}
//再写入原始数据
for (int i = 0; i < bytes.Length; ++i)
{
temps[i + passTemp.Length] = bytes[i];
}
//写入数据
bw.Write(temps);
AssetDatabase.Refresh();
Debug.Log("write over");
}
接下来是动态加载部分
//加密字符,和生成加密文件时的密码一致
string passStr = "Dxl";
//加载加密的dll文件,先解密,再使用
void LoadEncryDll()
{
//先解密,再调用
TextAsset tx = Resources.Load<TextAsset>("DllTest/TestDll");
if (tx == null)
{
Debug.Log("tx is null");
return;
}
byte[] passTemp = Encoding.UTF8.GetBytes(passStr);
byte[] dllbytes = new byte[tx.bytes.Length - passTemp.Length];
for (int i=passTemp.Length; i<tx.bytes.Length;++i)
{
dllbytes[i - passTemp.Length] = tx.bytes[i];
}
Assembly assembly = Assembly.Load(dllbytes);
if (assembly != null)
{
Type type = assembly.GetType("Test2019Dll.Class1");//类型
//静态方法
//public static void TestFunc1()
MethodInfo method1 = type.GetMethod("TestFunc1");
//public static void TestFunc2(string str)
MethodInfo method2 = type.GetMethod("TestFunc2");
//public static void TestFunc3(string str1, string str2)
MethodInfo method3 = type.GetMethod("TestFunc3");
//非静态方法
//public void TestFunc4()
MethodInfo method4 = type.GetMethod("TestFunc4");
//public void TestFunc5(string str)
MethodInfo method5 = type.GetMethod("TestFunc5");
//void TestFunc6()
MethodInfo method6 = type.GetMethod("TestFunc6", BindingFlags.NonPublic | BindingFlags.Instance);
//void TestFunc7(string str)
MethodInfo method7 = type.GetMethod("TestFunc7", BindingFlags.NonPublic | BindingFlags.Instance);
//调用静态无惨方法
method1.Invoke(null, null);
//调用静态有参方法
object[] pars2 = new object[1] { "hello,I'm test 2" };
method2.Invoke(null, pars2);
//调用静态有2个参数方法
object[] pars3 = new object[2] { "hello1", "hello2" };
method3.Invoke(null, pars3);
//调用非静态方法
object obj = Activator.CreateInstance(type);//绑定对象
method4.Invoke(obj, null);
object[] pars5 = new object[1] { "hello,I'm test 5" };
method5.Invoke(obj, pars5);
//调用私有方法
method6.Invoke(obj, null);
method7.Invoke(obj, pars5);
}
else
{
Debug.Log("oh ,on");
}
}