Why are generics not supported with PInvoke #46204
-
There's been many occasions where I've had to create several overloads of PInvoke functions when there is a reference argument that changes based on another flag argument. A perfect example of this would be In an ideal world you would simply have a |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
You can write a wrapper: [DllImport("SomeLibrary")]
private static extern void SomePInvokeMethod(IntPtr ptr);
private static void GenericPInvokeMethod<T>(ref T val) where T : unmanaged
{
fixed (T* ptr = &val)
{
SomePInvokeMethod((IntPtr)ptr);
}
} |
Beta Was this translation helpful? Give feedback.
-
@Dewera Great question. There are a few ways to answer this, let me offer you some.
Is there a technical limitation to supporting this? I can't honestly think of one in the current dynamic IL Stub system - (3) is the biggest and then of course efficiently determining which IL Stub to use. It would require a non-trivial amount of work that may or may not justify the outcome - I don't personally think it would be of much benefit. I could also see a case being made that there are some metadata issues but I don't know if that would actually be a problem. Also, we would need a C# language update for defining a Generic The comment from @acaly, #46204 (comment), would be my recommendation if someone was after such support at present. |
Beta Was this translation helpful? Give feedback.
-
Thank you! I didn't know of this feature in C11. I will say it seems a bit clunky, but definitely helps with the math functions and I am sure many other scenarios. I am sure it was an amazing standards meeting when the design was discussed :-) |
Beta Was this translation helpful? Give feedback.
@Dewera Great question. There are a few ways to answer this, let me offer you some.
Is there a technical limitation to supporting this? I can't honestly think of one in the current dynamic IL Stub system - (3) is the biggest and then of course efficiently determining which IL Stub to use. It would require a non-trivia…