betoesquivel

Programación Avanzada código dll tarea 9

Nov 4th, 2014
491
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <windows.h>
  2. #include <malloc.h>    
  3. #include <stdio.h>
  4. #include <tchar.h>
  5.  
  6. extern "C"
  7. {
  8.     typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION,PDWORD);
  9.  
  10.     __declspec(dllexport) int getCoreCount(){
  11.         LPFN_GLPI glpi;
  12.         BOOL done = FALSE;
  13.         PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
  14.         PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
  15.         DWORD returnLength = 0;
  16.         DWORD processorCoreCount = 0;
  17.         DWORD byteOffset = 0;
  18.         HINSTANCE hDll;
  19.  
  20.         hDll=LoadLibrary("kernel32.dll");
  21.         if (hDll==NULL) {
  22.             printf("ERROR!!!\n");
  23.             return(1);
  24.         }
  25.  
  26.         glpi = (LPFN_GLPI) GetProcAddress(hDll,"GetLogicalProcessorInformation");
  27.         if (NULL == glpi) {
  28.             printf("\nGetLogicalProcessorInformation is not supported.\n");
  29.             return (1);
  30.         }
  31.  
  32.         while (!done) {
  33.             DWORD rc = glpi(buffer, &returnLength);
  34.             if (FALSE == rc) {
  35.                 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
  36.                     if (buffer)
  37.                         free(buffer);
  38.                     buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(
  39.                             returnLength);
  40.                     if (NULL == buffer) {
  41.                         printf("\nError: Allocation failure\n");
  42.                         return (2);
  43.                     }
  44.                 } else {
  45.                     printf("\nError %d\n", GetLastError());
  46.                     return (3);
  47.                 }
  48.             } else {
  49.                 done = TRUE;
  50.             }
  51.         }
  52.  
  53.         ptr = buffer;
  54.  
  55.         while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
  56.             if (ptr->Relationship == RelationProcessorCore) {
  57.                 processorCoreCount++;
  58.             }
  59.             byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
  60.             ptr++;
  61.         }
  62.     /*
  63.         printf("Number of processor cores: %d\n",
  64.                  processorCoreCount);
  65.     */
  66.         free(buffer);
  67.  
  68.         FreeLibrary(hDll);
  69.         return processorCoreCount;
  70.     }
  71. }
Advertisement