Skip to content

Commit

Permalink
Fix InvalidProgramException when type is pointer
Browse files Browse the repository at this point in the history
  • Loading branch information
scott-xu committed Apr 8, 2022
1 parent 476135b commit 8624475
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/Ninject.Test/Ninject.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>
<IsPackable>false</IsPackable>
<Optimize>true</Optimize>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
19 changes: 19 additions & 0 deletions src/Ninject.Test/Unit/DynamicMethodInjectorFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,25 @@ public void CallsConstructorWithNullArgumentIfOneIsSpecified()
samurai.Should().NotBeNull();
samurai.Weapon.Should().BeNull();
}

[Fact]
public void CallsConstructorWithPointerArgument()
{
var consInfo = typeof(string).GetConstructor(new[] { typeof(char*) });
var injector = this.injectorFactory.Create(consInfo);
unsafe
{
var fchar = 'f';
var o = Pointer.Box(&fchar, typeof(char*));

char* uf = (char*)Pointer.Unbox(o);

var s = new string(uf);

var fstring = injector.Invoke(new[] { Pointer.Box(&fchar, typeof(char*)) });
fstring.Should().Be("f");
}
}
}

public class WhenPropertyInjectorIsInvoked : DynamicMethodInjectorFactoryContext
Expand Down
16 changes: 14 additions & 2 deletions src/Ninject/Injection/DynamicMethodInjectorFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ namespace Ninject.Injection
/// </summary>
public class DynamicMethodInjectorFactory : NinjectComponent, IInjectorFactory
{
private static readonly MethodInfo UnboxPointer = typeof(Pointer).GetMethod("Unbox");

/// <summary>
/// Gets or creates an injector for the specified constructor.
/// </summary>
Expand Down Expand Up @@ -140,8 +142,18 @@ private static void EmitMethodCall(ILGenerator il, MethodInfo method)

private static void EmitUnboxOrCast(ILGenerator il, Type type)
{
var opCode = type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass;
il.Emit(opCode, type);
if (type.IsValueType)
{
il.Emit(OpCodes.Unbox, type);
}
else if (type.IsPointer)
{
il.Emit(OpCodes.Call, UnboxPointer);
}
else
{
il.Emit(OpCodes.Castclass, type);
}
}

private static string GetAnonymousMethodName()
Expand Down

0 comments on commit 8624475

Please # to comment.