Jul 15, 2007

Use macro for dynamic linking of DLL

Dynamic linking of DLL needs more code than static linking. We have to use GetProcAddress() API for each functions. It may cause bug if we make typo.
m_fnSetCommInfo =
  reinterpret_cast< FnSetCommInfo >(
  ::GetProcAddress( m_hLibrary, "SetCommInfo" ) );
m_fnGetCommInfo =
  reinterpret_cast< FnGetCommInfo >(
  ::GetProcAddress( m_hLibrary, "GetComInfo" ) ); // <-- Ahh !!
Define statement prevents such bug.
#define LOAD_FUNCTION(name) \
  m_fn##name = reinterpret_cast< Fn##name >( \
  ::GetProcAddress( m_hLibrary, #name ) );

LOAD_FUNCTION( SetCommInfo );
LOAD_FUNCTION( GetCommInfo );
This is easier to read. Macro sometimes prevents bug.

No comments: