malloc: *** error for object 0x1018ad6a0: pointer being freed was not allocated

.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);
    }
}

mm 中的externC代码如下:

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");
    }
}

猜你喜欢

转载自blog.csdn.net/u012138730/article/details/82896060