title: C++ Access violation calling function from dll
body: <p>I am developing an application that will access smart cards using the standard PKCS#11. At this moment the application is working very well both on Ubuntu and OS X. Now I am porting it to Windows, but I am getting an "access violation" exception whenever I call functions from the pkcs#11 library, which is linked at runtime.</p>
  
  <p>Below I tried to reproduce a SSCCE of my code (The place where the exception is happening is identified with a comment).</p>
  
  <pre><code>void * libraryHandle = NULL;
  CK_RV   rv;
  CK_C_GetFunctionList pC_GetFunctionList;
  CK_FUNCTION_LIST_PTR functions;
  
  
  libraryHandle = LoadLibrary(L"C:\\WINDOWS\\system32\\pteidpkcs11.dll");
  if (libraryHandle == NULL)
  {
      printf("Library not loaded\n");
      exit(1);
  }
  
  pC_GetFunctionList = (CK_C_GetFunctionList) GetProcAddress((HMODULE)libraryHandle, "C_GetFunctionList");
  
  if (pC_GetFunctionList == NULL)
  {
      printf("Function not loaded\n");
      FreeLibrary((HMODULE)libraryHandle);
      exit(1);
  }
  
  rv = (*pC_GetFunctionList) (&amp;functions);
  assert(rv == CKR_OK);
  printf("Point A\n");
  
  if(functions == NULL)
  { 
      printf("Functions not loaded\n");
      FreeLibrary((HMODULE)libraryHandle);
      exit(1);        
  }
  
  printf("%u - %u\n",functions-&gt;version.major, functions-&gt;version.minor); // Prints without problems
  rv = (*functions-&gt;C_Initialize) (NULL_PTR); //THIS IS THE PLACE WHERE I AM GETTING THE ACCESS VIOLATION
  assert(rv == CKR_OK);
  
  //printf("Point B\n");
  
  FreeLibrary((HMODULE)libraryHandle);
  </code></pre>
  
  <p>When I debug the application the structure "CK_FUNCTION_LIST_PTR functions" seems to be valid.</p>
  
  <p>Does anyone know what is causing this exception?</p>
  
  <p>I am using Visual Studio 2010 Ultimate and Windows XP SP3.</p>
  
  <p>Thanks!</p>
  
  <p>(PS: I have already tried to load the function "C_Initialize" using "GetProcAddress" from the library, and it worked)</p>
  
  <p>--- Edit</p>
  
  <p>CK_FUNCTION_LIST definition</p>
  
  <pre><code>struct CK_FUNCTION_LIST {
  
    CK_VERSION    version;  /* Cryptoki version */
  
  /* Pile all the function pointers into the CK_FUNCTION_LIST. */
  /* pkcs11f.h has all the information about the Cryptoki
   * function prototypes. */
  #include "pkcs11f.h"
  
  };
  </code></pre>
  
  <p>Full headers in: 
    <a href="http://www.rsa.com/rsalabs/node.asp?id=2133" rel="nofollow">http://www.rsa.com/rsalabs/node.asp?id=2133</a></p>