Replies: 1 comment
-
I think Maybe we could go one step further and hide away the unsafe aspect by wrapping it: namespace PythonApi {
public int PyBuffer_FillInfo(IntPtr arg0, IntPtr arg1, IntPtr arg2, nint arg3, int arg4, int arg5) {
unsafe {
return UnmanagedFunctions.PyBuffer_FillInfo(arg0, arg1, arg2, arg3, arg4, arg5);
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The current convention in code is that to store pointers to unmanaged functions,
IntPtr
is used. To call such an unmanaged function, a delegate is created and invoked. Example (fromIC_bytes_buffer_getbuffer
):This is not very efficient, and since C# 9 we have function pointers:
Note:
Cdecl
is required forNETFRAMEWORK
, and not required forNET
, I think. On .NET, the framework should be able to determine the OS-default calling convention at runtime. This may incur some runtime cost, but the code is portable between OSes. Since the unmanaged DLL is not portable anyway, there is probably no good reason not to make the managed DLL OS-specific as well.Also, using
IntPtr
is not type-safe, since no signature checking is done or even possible. Ironically, safer code (in the literal sense) requires anunsafe
block. Ideally, a CPython API function would be already be declared as a function pointer with a proper signature inPythonApi.Generated.cs
. Instead of:we could have
Then the API call could be:
This could introduce a number of
unsafe
code blocks, but the code will be actually safer, and not to forget, faster too. However, declaring classesPythonApi
andPythonMapper
asunsafe
makes a lot of sense and will reduce the number ofunsafe
blocks or methods in the code.The only place where
IntPtr
storing a function pointer will still be needed is if the value needs to be boxed.The disadvantage of this proposal is that it is not possible to give a function pointer type a name (unlike in C, where
typedef
can be used). I think in practice this should not be a big hardship, as most (if not all) definitions of actual values are in the generated code, and in some other places, perhapsvar
could be used.Beta Was this translation helpful? Give feedback.
All reactions