/**
* 获取Il2Cpp的实例化对象的值
*
* @param objValue 对象
* @returns 对象的值字符串
*/
function get2cppObjectValue(objValue: Il2Cpp.Object | Il2Cpp.ValueType | NativePointer): string {
try {
// 检查是否为空
if (!objValue || objValue == null || objValue == undefined || typeof objValue != "object" || objValue.isNull()) {
if (typeof objValue === "string") {
return objValue;
} else if (typeof objValue === "number") {
return objValue;
}
return "";
}
// 如果是指针类型,那么转换成对象
if (objValue instanceof NativePointer) {
objValue = new Il2Cpp.Object(objValue);
if (!objValue || objValue.isNull()) {
return "";
}
}
const clz = objValue instanceof Il2Cpp.Object ? objValue.class : objValue instanceof Il2Cpp.ValueType ? objValue.type.class : null;
if (!clz || clz == null || clz == undefined || clz.isNull()) {
return "";
}
// 最终字符串
let jsonStr = "{" + "\"" + clz.name + "\":{";
const readNativeIterator = (block) => {
const array = [];
const iterator = Memory.alloc(Process.pointerSize);
let handle = block(iterator);
while (!handle.isNull()) {
array.push(handle);
handle = block(iterator);
}
return array;
}
// 开始逐个字段获取值
const fields = readNativeIterator(_ => Il2Cpp.api.classGetFields(clz.handle, _)).map(_ => new Il2Cpp.Field(_).withHolder(objValue))
let lastNum = 0;
fields.forEach((field: Il2Cpp.Field) => {
const fieldName = field.name;
const fieldType = field.type;
const fieldValue = field.value;
// 如果是空值,那么跳过
if (fieldValue == null || fieldValue == undefined || (fieldValue instanceof Il2Cpp.Object && fieldValue.isNull())) {
return;
}
// 如果是对象,那么递归获取
if (fieldValue instanceof Il2Cpp.Object) {
jsonStr += "\"" + fieldName + "\":" + get2cppObjectValue(fieldValue) + ",";
}
else if (fieldType.typeEnum == Il2Cpp.Type.enum.string) {
jsonStr += "\"" + fieldName + "\":" + fieldValue + ",";
} else if (fieldType.typeEnum == Il2Cpp.Type.enum.array) {
jsonStr += "\"" + fieldName + "\":[";
if (lastNum > 0) {
for (let i = 0; i < lastNum; i++) {
if (i >= fieldValue.length) {
break;
}
const value = fieldValue.get(i);
if (value == null || value == undefined || value.toString() == "null") {
continue;
}
jsonStr += get2cppObjectValue(value) + ",";
}
jsonStr = jsonStr.substring(0, jsonStr.length - 1);
}
jsonStr += "],";
} else {
if (typeof fieldValue === "number") {
lastNum = fieldValue;
}
if (fieldValue.toString() === "") {
jsonStr += "\"" + fieldName + "\":\"\",";
} else {
// 如果是普通类型,那么直接获取值
jsonStr += "\"" + fieldName + "\":" + fieldValue + ",";
}
}
});
jsonStr = jsonStr.substring(0, jsonStr.length - 1);
jsonStr += "}}";
return jsonStr;
} catch (e: any) {
console.error("Il2CppMethod getObjectValue Error =>", e.stack);
}
return "";
};