Skip to content

Instantly share code, notes, and snippets.

@xVir
Created March 12, 2015 12:05
Show Gist options
  • Save xVir/5ce63715bcde4c7ccfa0 to your computer and use it in GitHub Desktop.
Save xVir/5ce63715bcde4c7ccfa0 to your computer and use it in GitHub Desktop.
Unity and codegeneration

While working on Unity plugin project I need to map JSON to the C# objects. For this task I used modification of the fastJSON library. But fastJSON use codegeneration for creating special methods for reading/writing object properties. It looks like:

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
if (fieldInfo.FieldType.IsValueType)
    il.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
il.Emit(OpCodes.Stfld, fieldInfo);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);

This solution provide great performance, but make it impossible to use this library in the iOS environment. To fix this I add option to the JSON parameters class to use alternative approach for creating methods for reading/writing object properties. Approach is to use anonymous methods:

if (parameters.WithoutDynamicMethodsGeneration) 
{
	return (target, val) =>
	{
		fieldInfo.SetValue(target, val);
		return target;
	};	
}

This fix implemented in commit e52135c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment