Share via


Using the Code Examples

Throughout this documentation, code examples are used to illustrate coding practices and procedures. These examples are intended simply to show how to accomplish tasks, and are not intended for direct use in applications.

Each code example is encapsulated in a function so that it is self-contained. These functions are not necessarily intended to meet the requirements of real-world applications. If you want to use code from an example in your application, you may need to take the code out of the function.

For simplicity, none of the examples provides robust error checking. The example code functions respond to errors by releasing resources and returning without generating any error messages. If you use this code in your applications, you should expand error handling to provide the user with information about the problem. It is also important to add parameter checks to the functions.

Common Macros

The code examples use the following macros to reduce length and automate common tasks.

The SAFE_RELEASE macro releases an interface reference and sets the interface pointer to NULL. Because it first checks the pointer for NULL, this macro can be safely used when you are not certain of the status of the pointer:

#ifndef SAFE_RELEASE
#define SAFE_RELEASE(x) \
   if(x != NULL)        \
   {                    \
      x->Release();     \
      x = NULL;         \
   }
#endif

The SAFE_ARRAY_DELETE macro is the analog of SAFE_RELEASE for dynamically allocated arrays (like strings):

#ifndef SAFE_ARRAY_DELETE
#define SAFE_ARRAY_DELETE(x) \
   if(x != NULL)             \
   {                         \
      delete[] x;            \
      x = NULL;              \
   }
#endif

The GOTO_EXIT_IF_FAILED macro checks an HRESULT and, if it contains a failed code, jumps to Exit, which is an identifier marking the exit point of the function:

#ifndef GOTO_EXIT_IF_FAILED
#define GOTO_EXIT_IF_FAILED(hr) if(FAILED(hr)) goto Exit
#endif

Functions that are set up to use this macro are structured like the following example:

HRESULT SomeFunction()
{
    HRESULT hr = S_OK;
    ...
    hr = pInterface->Method();
    GOTO_EXIT_IF_FAILED(hr);
    ...
Exit:
    // Release any allocated resources.
    return hr;
}

This style of error handling enables you to break out of a function quickly when an error occurs, while still being able to release any allocated resources.

See Also

About the Windows Media Audio and Video Codec and DSP APIs

 

 

Send comments about this topic to Microsoft

Build date: 4/7/2010