-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C# should provide better interop with unmanaged function pointers. #13240
Comments
@jaredpar I think this is related to something you've been working on. |
I talked with @jaredpar briefly and he had some ideas on how we could do this in a 'safe' manner (thus removing the requirement for 'function pointer' support to only be allowed in an unsafe code block). I'll let him add his thoughts on the matter (or will add a brief detailing of our discussion if he gives me the go-ahead) |
This feature would be welcome by projects such as SharpDX that makes its own COM wrappers for lots of Windows APIs (currently it uses the While searching about this topic I saw a post by Eric Lippert on StackOverflow http://stackoverflow.com/questions/36558996/how-to-implement-c-style-function-pointers-in-c-without-using-delegates where he explains the difficulties of finding the right syntax. One workaround I can think of is to make for delegates the same thing that is currently in place for In an unsafe context I can use Maybe the solution would be to:
The main advantage of this solution is that no new syntax is needed for the language, it is only a compiler thing. |
Ported to dotnet/csharplang#80 |
Issue
C# has no mechanism for declaring unmanaged function pointers.
While there are a couple of mechanisms designed to work with and call unmanaged function pointers, these mechanisms may:
Workaround
Declare the function pointer using
IntPtr
and then use theMarshal.GetDelegateForFunctionPointer
method to convert to a managedDelegate
. Such as:-or-
Declare a managed delegate and rely on the marshalling behavior to convert as appropriate. Such As:
Proposal
The C# language should be extended to support function pointers in an unsafe context. Such as:
The compilation should fail if
unsafe
is missing.Advantages
The compiler could take advantage of the fact this is an unsafe function pointer and emit the
calli
instruction when invoking.The compiler could provide some level of type safety when invoking the function pointer (ensuring the arguments passed in match the types required).
This would allow better interop with unmanaged languages and types that use function pointers.
This would allow a user to more readily implement VTBLs for unmanaged interop when required.
The text was updated successfully, but these errors were encountered: