How can we get the signature of a function pointer from metadata? #4256
-
Hello everyone. In recent days I found some "interesting" problems on function pointers. The first one is, I know that the function pointers will be translated into an StringBuilder AppendRange<TElement, TOther>(
this StringBuilder,
IEnumerable<TElement?>,
delegate*<in TElement?, TOther?>); The method does work. However, we must specify each generic parameters because C# can't recognize them: #nullable enable
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
unsafe
{
string s = new StringBuilder()
.AppendRange<int, string>(Enumerable.Range(1, 10), &converter) // Here.
.ToString();
Console.WriteLine(s);
}
static string converter(int v) => $"{v}, ";
public static class C
{
public static unsafe StringBuilder AppendRange<TElement, TOther>(
this StringBuilder @this,
IEnumerable<TElement?> contentList,
delegate*<TElement?, TOther?> converter)
{
foreach (var content in contentList)
{
@this.Append(converter(content)?.ToString() ?? string.Empty);
}
return @this;
}
} If we don't specify Another question is ... LINQ. LINQ keywords calls corresponding extension methods if the type contains implemented and matched one. However, C# now can't allow us using function pointers to instead of delegates. Delegates are powerful, but sometimes I prefer to use function pointers to reduce some unnecessary encapsulation on method invocation. Like this: #nullable enable
using System;
using System.Collections.Generic;
unsafe
{
int result = from bit in 17 where (bit & 1) != 0 select bit;
Console.WriteLine(result);
}
public static class C
{
public static IEnumerator<int> GetEnumerator(this int @this) =>
@this.GetAllSets().GetEnumerator();
public static IEnumerable<int> GetAllSets(this int @this)
{
if (@this == 0)
{
yield break;
}
for (int i = 0; i < 16; i++, @this >>= 1)
{
if ((@this & 1) != 0)
{
yield return i;
}
}
}
public static int Where(this int @this, Predicate<int> condition) // Here.
{
int result = 0;
foreach (int i in @this)
{
if (condition(i))
{
result |= 1 << i;
}
}
return result;
}
} I can't replace the delegate type with function pointers such as If the function pointers can be recognized, does it mean C# can allow us omitting generic parameter list in a generic method, or using LINQ without normal delegate types? I don't know whether there are other complex reasons that function pointers can't be a parameter in LINQ extension methods or omitting in generic method at present. Is it by design? So... Any consideration on it? Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Ok, so in order:
|
Beta Was this translation helpful? Give feedback.
Ok, so in order: