Why is this C# code not type-safe and why does this other bit make it type-safe?
This is from the midi-dot-net http://code.google.com/p/midi-dot-net/ library:
static class Win32API
{ ...
#region Non-Typesafe Bindings
// The bindings in this section are not typesafe, so we make them private
// and provide typesafe variants
[DllImport("winmm.dll", SetLastError = true)]
private static extern MMRESULT midiOutOpen(out HMIDIOUT lphmo,
UIntPtr uDeviceID, MidiOutProc dwCallback, UIntPtr dwCallbackInstance,
MidiOpenFlags dwFlags);
...
/// <summary>
/// Opens a MIDI output device.
/// </summary>
/// NOTE: This is adapted from the original Win32 function in order
/// to make it typesafe.
///
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711632(VS.85).aspx
public static MMRESULT midiOutOpen(out HMIDIOUT lphmo,
开发者_开发技巧 UIntPtr uDeviceID, MidiOutProc dwCallback, UIntPtr dwCallbackInstance)
{
return midiOutOpen(out lphmo, uDeviceID, dwCallback, dwCallbackInstance,
dwCallback == null ? MidiOpenFlags.CALLBACK_NULL :
MidiOpenFlags.CALLBACK_FUNCTION);
}
How does this last function make the win32 call type-safe?
Adapting my comment as an answer...
I don't know what makes the revised version type safe, but it is a safer (less error-prone) call.
It is possible to call dll function midiOutOpen
parameter with a null
dwCallbackInstance
with MidiOpenFlags = MidiOpenFlags.CALLBACK_FUNCTION
. If the dll function does not check for null then it will cause some disturbance.
With the adopted function the midiOutOpen
parameter is derived so no danger.
I don't know what SetLastError = true
is but I would think the wrapper might have checked the LastError
and acted appropriately (throw exception?)
精彩评论