2011-10-03 16 views
3

这是从MIDI点网http://code.google.com/p/midi-dot-net/库:为什么这个C#代码不是类型安全的,为什么这个其他位使它类型安全?

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); 
    } 

请问这个最后的功能使Win32调用类型安全的?

+6

我不认为它是类型安全的,但它是更安全,因为' MidiOpenFlags'只有正确的值。 –

回答

2

适应作为一个答案我的意见......

我不知道是什么让修改后的版本类型安全的,但它是一个更安全(不容易出错)调用。

有可能调用dll函数midiOutOpen参数与nulldwCallbackInstanceMidiOpenFlags = MidiOpenFlags.CALLBACK_FUNCTION。如果dll函数没有检查null,那么它会造成一些干扰。

随着采用函数midiOutOpen参数派生出来,所以没有危险。

我不知道是什么SetLastError = true是但我认为包装可能已经检查了LastError并适当地采取行动(抛出异常?)

相关问题