Skip to content

Commit

Permalink
Adding tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hez2010 committed Jan 23, 2024
1 parent 21c6202 commit a10142c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/tests/Interop/MarshalAPI/FunctionPointer/FunctionPointer.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;

Expand Down Expand Up @@ -111,4 +112,53 @@ public static void RunGetDelForOutIntTest()
}
Assert.Equal(expectedValue, outVar);
}

[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
static int UnmanagedExportedFunction(float arg)
{
return Convert.ToInt32(arg);
}

class GenericCaller<T>
{
internal static unsafe T GenericCalli<U>(void* fnptr, U arg)
{
return ((delegate* unmanaged<U, T>)fnptr)(arg);
}
}

[Fact]
public static void RunGenericFunctionPointerTest()
{
Console.WriteLine($"Running {nameof(RunGenericFunctionPointerTest)}...");
int outVar = 0;
int expectedValue = 42;
unsafe
{
outVar = GenericCaller<int>.GenericCalli((delegate* unmanaged[Cdecl]<float, int>)&UnmanagedExportedFunction, 42.0f);
}
Assert.Equal(expectedValue, outVar);
}

[Fact]
public static void RunInvalidGenericFunctionPointerTest()
{
Console.WriteLine($"Running {nameof(RunInvalidGenericFunctionPointerTest)}...");
unsafe
{
nint lib = nint.Zero;
try
{
lib = NativeLibrary.Load(nameof(FunctionPointerNative));
Assert.Throws<MarshalDirectiveException>(() => GenericCaller<string>.GenericCalli((delegate* unmanaged[Cdecl]<string, string>)NativeLibrary.GetExport(lib, "ReturnParameter"), "test"));
}
finally
{
if (lib != nint.Zero)
{
NativeLibrary.Free(lib);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,8 @@ extern "C" DLL_EXPORT void FillOutIntParameter(intptr_t *p)
*p = 50;
}

extern "C" DLL_EXPORT intptr_t* ReturnParameter(intptr_t *p)
{
return p;
}

0 comments on commit a10142c

Please sign in to comment.