unity工程接iossdk的时候遇到的错误:
1.无法弹出他们sdk的登陆界面。
让他们加日志,这边测试
self.bgView.width 不能这么获取,需要self.bgViw.frame.width
原因是他们自己工程对UIView加了Category--》UIView+Size,可以通过self.bgView.width来获取宽和高,其实真正调用的的view.frame.width,而我们的工程没有扩展,所以需要通过原始接口self.bgView.frame.width。猜测他没有把这个扩展打入包中给我们。
最后解决是他那边修改成了self.bgView.frame.width。
2.调用一个ios端实现的函数的时候(在c#中调用),出现指针被释放的错误
C#代码进行 IL2CPP,即.Net运行时固化成C++以后,对一个string进行的变量,会进行free的操作,而如果ios端库函数不是用malloc申请的对象,free就会出现问题了。
unity中客户端即csharp中,要调用ios端定义的函数(ios段定义的这个函数返回值是字符串,代表的是channelID),csharp需要调用接口获取到这个字符串。
下面还原一下问题2的过程:
目录
1.cs文件 ——调用ios库函数
.cs 中的原始代码如下:
public class JsonTest : MonoBehaviour {
// Use this for initialization
[DllImport("__Internal")]
private static extern string xxxsdk_channelId();
void Start()
{
string strChannelID = xxxsdk_channelId();
Debug.Log("strChannelID\t" + strChannelID);
}
}
调用就是下面这句:
string strChannelID = xxxsdk_channelId();
2.mm文件——不同接口实现
mm 中的接口实现如果为方式一或二或三——没有用malloc分配空间,虽然接口本身没有问题,但是由于csharp中的接口声明在IL2CPP的时候调用了free函数,就会出现题目所示的错误。
需要修改为方式四——用malloc分配空间。
方式一
extern "C" {
const char* xxxsdk_channelId()
{
NSString* channelid = @"111";
return [channelid UTF8String];
}
}
方式二
extern "C" {
char* xxxsdk_channelId()
{
return const_cast<char*>([@"111" UTF8String]);
}
}
方式三
extern "C" {
char* xxxsdk_channelId()
{
return "111";
}
}
或者等等都有问题 出现的错误是
malloc: *** error for object 0x1018ad6a0: pointer being freed was not allocated。
错误原因
原因是因为,对 原始C#代码 进行 IL2CPP的时候,对于:
[DllImport("__Internal")]
private static extern string xxxsdk_channelId();
.Net运行时固化成C++以后的结果为如下:(xcode中看Bulk_Assembly-CSharp_X.cpp)
extern "C" char* DEFAULT_CALL xxxsdk_channelId();
// 对于 private static extern string xxxsdk_channelId();的翻译
// System.String JsonTest::xxxsdk_channelId()
extern "C" String_t* JsonTest_xxxsdk_channelId_m2725694806 (Il2CppObject * __this /* static, unused */, const MethodInfo* method)
{
typedef char* (DEFAULT_CALL *PInvokeFunc) ();
// 执行 .mm 文件 中定义的 xxxsdk_channelId
// Native function invocation
char* returnValue = reinterpret_cast<PInvokeFunc>(xxxsdk_channelId)();
// 把char* 转换成 C#中的String_t* Marshal类
// Marshaling of return value back from native representation
String_t* _returnValue_unmarshaled = NULL;
_returnValue_unmarshaled = il2cpp_codegen_marshal_string_result(returnValue);
// returnValue是通过 malloc 申请的,所以要释放,如果本身不是通过malloc的话,调用这句话就会出错。
// Marshaling cleanup of return value native representation
il2cpp_codegen_marshal_free(returnValue);
returnValue = NULL;
return _returnValue_unmarshaled;
}
即当调用
il2cpp_codegen_marshal_free(returnValue);的时候出现的错误:
malloc: *** error for object 0x1018ad6a0: pointer being freed was not allocated
不能free,因为以上的char* 都不是 malloc出来的。
正确方式:
所以修改 .mm , 写一个malloc分配字符串的接口
char* MakeStringCopy(const char* string)
{
if (string == NULL)
return NULL;
char* res = (char*)malloc(strlen(string) + 1);
strcpy(res, string);
return res;
}
extern "C" {
char* xxxsdk_channelId()
{
return MakeStringCopy("134");
}
}