Skip to content

Commit

Permalink
Eliminate unnecessary ChangeType calls
Browse files Browse the repository at this point in the history
  • Loading branch information
azurefx committed Mar 30, 2020
1 parent 2e99bb1 commit cde12fa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
4 changes: 2 additions & 2 deletions CLRBridge/CLRBridge.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyVersion>0.1.0.0</AssemblyVersion>
<Version>0.1.0</Version>
<AssemblyVersion>0.1.1.0</AssemblyVersion>
<Version>0.1.1</Version>
</PropertyGroup>

</Project>
12 changes: 9 additions & 3 deletions CLRBridge/Callback.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,15 @@ private static Delegate CompileHandlerInvocation(Type delegateType, Func<object[
var target = handler.Target == null ? null : Expression.Constant(handler.Target);
var parametersObj = parameters.Select(parm => Expression.Convert(parm, typeof(object)));
var call = Expression.Call(target, handler.Method, Expression.NewArrayInit(typeof(object), parametersObj));
ChangeTypeMethod method = Convert.ChangeType;
var changeType = Expression.Call(method.Method, call, Expression.Constant(invokeFun.ReturnType));
var body = invokeFun.ReturnType == typeof(void) ? (Expression)call : Expression.Convert(changeType, invokeFun.ReturnType);
var ret = Expression.Variable(typeof(object));
ChangeTypeMethod changeTypeMethod = Convert.ChangeType;
var typeCast = Expression.Block(new[] { ret },
Expression.Assign(ret, call),
Expression.Condition(Expression.TypeIs(ret, invokeFun.ReturnType),
ret,
Expression.Call(changeTypeMethod.Method, ret, Expression.Constant(invokeFun.ReturnType)))
);
var body = invokeFun.ReturnType == typeof(void) ? (Expression)call : Expression.Convert(typeCast, invokeFun.ReturnType);
return Expression.Lambda(delegateType, body, parameters).Compile();
}
}
Expand Down

0 comments on commit cde12fa

Please sign in to comment.