elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Mensajes
Páginas: 1 2 3 4 5 6 7 8 9 10 11 [12] 13 14 15 16 17 18 19 20 21
111  Programación / Programación C/C++ / Clases de almacenamiento en: 26 Marzo 2013, 22:38 pm
Hola me decidí a crear un proyecto simple que trate de aplicar todas las keywords del lenguaje con respecto a las clases o directivas de almacenamiento. No creo haber utilizado todos los casos posibles, pero me parece que el resultado es un código que explica muy bien al menos como usar los  casos más generales.
Las keywords en cuestión son estas:

extern
static
auto
register
inline
mutable
volatile


No me pregunten sobre 'mutable' y 'volatile' porque no las he usado nunca XD.

El programa trata de mostrar información por pantalla para dejar en claro el lugar de almacenamiento de las variables utilizadas, y su valor de inicialización.
También se deja en claro el uso de estas directivas en funciones.

Otra cosa que quiero aclarar que 'extern' es por defecto, pero yo lo especifiqué explícitamente para esta demostración.

Y también muestro una forma de usar una función que normalmente no se puede usar de un archivo fuente a otro, pero mediante su dirección se puede.

Dejo el código.

main.cpp
Código
  1. //
  2. // By 85
  3. // elhacker.net
  4. // etalking.com.ar
  5. // boyscout_etk@hotmail.com
  6. // 2013
  7. //
  8.  
  9. ////////////////////////////////////////////////////////////////////////////////////////////////
  10.  
  11. #include<windows.h>
  12. #include<stdio.h>
  13.  
  14. #include "inclusiones.h"
  15.  
  16. ////////////////////////////////////////////////////////////////////////////////////////////////
  17.  
  18. ////////////////////////////////////////////////////////////////////////////////////////////////
  19.  
  20. char* palabra[] = { "Hola", "Mi", "Nombre", "Es", "David", "Y", "El", "Tuyo?" };
  21.  
  22. char* msgList[] = {
  23.  
  24.    "HAHAHA",
  25.    "HOHOHO",
  26.    "HUHUHU",
  27.    0
  28. };
  29.  
  30. char* cadenaCortada = "Hola\nMe\nDices\nTu\nNombre\n?\0";
  31.  
  32. ////////////////////////////////////////////////////////////////////////////////////////////////
  33.  
  34. extern int variable1;
  35. extern int variable2 = 0;
  36. int variable3        = 0;// Es extern por defecto!, aunque no se especifique
  37.  
  38. extern char cadena1[] = "AAAAAAAAAAAAAAA";
  39. extern char cadena2[] = "AAAAAAAAAAAAAAA";
  40. char cadena3[] =        "BBBBBBBBBBBBBBB";
  41.  
  42. static int x;
  43. static int y = 0;
  44.  
  45. ////////////////////////////////////////////////////////////////////////////////////////////////
  46. // MAL! (Revisar los conceptos de cada clase de almacenamiento)
  47.  
  48. //auto int varmal1;
  49. //auto int varmal2=0;
  50.  
  51. //register int varmal3;
  52. //register int varmal4=0;
  53.  
  54. ////////////////////////////////////////////////////////////////////////////////////////////////
  55.  
  56. //Mutable sólo puede ser aplicada a miembros de clases
  57. //Sirve para que determinados miembros de un objeto de una estructura o
  58. //clase declarado como constante, puedan ser modificados.
  59.  
  60. ////////////////////////////////////////////////////////////////////////////////////////////////
  61.  
  62. //Volatile se usa con objetos que pueden ser modificados desde el exterior del programa,
  63. //mediante procesos externos.
  64. //Es frecuente encontrar juntos los modificadores volatile y const:
  65. //si la variable se modifica por un proceso externo, no tiene mucho sentido que el
  66. //programa la modifique.
  67.  
  68. volatile int varilo1;
  69. volatile int varilo2 = 0;
  70.  
  71. volatile int  ilvolo1 = 10;
  72. //int*          p_ilvolo1 = &ilvolo1;// MAL!
  73. volatile int* p_ilvolo1 = &ilvolo1;
  74.  
  75. ////////////////////////////////////////////////////////////////////////////////////////////////
  76. // HACK
  77.  
  78. // El hack consiste en guardar las direcciones de las funciones 'static' y usar
  79. // punteros a función en las otras unidades de compilación.
  80. // De esa forma, el compilador no lo restringe.
  81.  
  82. DWORD add_Func1_StringCompare = (DWORD)&Func1_StringCompare;
  83. DWORD add_Func2_StringLength = (DWORD)&Func2_StringLength;
  84. DWORD add_Func3_StripReturn = (DWORD)&Func3_StripReturn;
  85.  
  86. ////////////////////////////////////////////////////////////////////////////////////////////////
  87.  
  88. static int Func1_StringCompare(char* q, char* a)
  89. {
  90.     do
  91.     {
  92.        if( *q!=*a )
  93.             return -1;
  94. if( !*q )
  95.     break;
  96. q++;
  97.         a++;
  98.     } while( *q );
  99.     return 0;
  100. }
  101.  
  102. ////////////////////////////////////////////////////////////////////////////////////////////////
  103.  
  104. static unsigned int Func2_StringLength(const char* f){
  105.  
  106. INT i=0;
  107.        while(*f++) i++;
  108.        return i;
  109. }
  110.  
  111. ////////////////////////////////////////////////////////////////////////////////////////////////
  112.  
  113. static void Func3_StripReturn(char* str)
  114. {
  115. for(register unsigned int i=0;i<strlen(str);i++)
  116. if (str[i]==10 || str[i]==13) {
  117. str[i]=' ';
  118. }
  119. }
  120.  
  121. ////////////////////////////////////////////////////////////////////////////////////////////////
  122. ////////////////////////////////////////////////////////////////////////////////////////////////
  123. ////////////////////////////////////////////////////////////////////////////////////////////////
  124.  
  125. void inline Func4_MostrarCadenas1(){// Inline es sólo para funciones
  126.  
  127. for(int i=0; i<(sizeof(palabra)/sizeof(palabra[0])); ++i)
  128. {
  129. printf("%d = %s\n", i, palabra[i]);
  130. }
  131. }
  132.  
  133. ////////////////////////////////////////////////////////////////////////////////////////////////
  134.  
  135. inline void Func5_MostrarMensajes1(){// Inline es sólo para funciones
  136.  
  137. for(char** i = msgList; *i; i++)
  138. {
  139. MessageBox(0, *i, *i, 0);
  140. }
  141. }
  142.  
  143. ////////////////////////////////////////////////////////////////////////////////////////////////
  144.  
  145. extern void Func6_getRAM(char* buf){
  146.  
  147. MEMORYSTATUS Status;
  148.        ZeroMemory(&Status, sizeof(Status));
  149.        Status.dwLength = sizeof(Status);
  150.        GlobalMemoryStatus(&Status);
  151.        DWORD dwRAM = (DWORD)(Status.dwTotalPhys/(1024*1024));
  152.        wsprintf(buf, "%d MB", dwRAM);
  153. }
  154.  
  155. ////////////////////////////////////////////////////////////////////////////////////////////////
  156.  
  157. void Func7_Variables1(){
  158.  
  159. // Valores de inicio y lugar de almacenamiento de las variables
  160. //
  161.  
  162. putchar(10);
  163.  
  164. int var1;
  165. int var2 = 0;
  166. static int var3;
  167. static int var4 = 0;
  168. volatile int var5;
  169. volatile int var6=0;
  170.  
  171. printf("variable local sin inicializar:        %d\n", var1);
  172. printf("variable local inicializada:           %d\n", var2);
  173. printf("variable local static sin asignar:     %d\n", var3);
  174. printf("variable local static asignada:        %d\n", var4);
  175. printf("variable local volatile sin asignar:   %d\n", var5);
  176. printf("variable local volatile asignada:      %d\n", var6);
  177. // printf("variable global sin asignar:           %d\n", variable1);
  178. printf("variable global asignada.              %d\n", variable2);
  179. printf("variable global asignada:              %d\n", variable3);
  180. printf("variable global static sin asignar:    %d\n", x);
  181. printf("variable global static asignada:       %d\n", y);
  182. printf("variable global volatile sin asignar:  %d\n", varilo1);
  183. printf("variable global volatile asignada:     %d\n", varilo2);
  184.  
  185.  
  186. printf("add variable local sin inicializar:        0x%X\n", &var1);
  187. printf("add variable local inicializada:           0x%X\n", &var2);
  188. printf("add variable local static sin asignar:     0x%X\n", &var3);
  189. printf("add variable local static asignada:        0x%X\n", &var4);
  190. printf("add variable local volatile sin asignar:   0x%X\n", &var5);
  191. printf("add variable local volatile asignada:      0x%X\n", &var6);
  192. // printf("add variable global sin asignar:           0x%X\n", &variable1);
  193. printf("add variable global asignada.              0x%X\n", &variable2);
  194. printf("add variable global asignada:              0x%X\n", &variable3);
  195. printf("add variable global static sin asignar:    0x%X\n", &x);
  196. printf("add variable global static asignada:       0x%X\n", &y);
  197. printf("add variable global volatile sin asignar:  0x%X\n", &varilo1);
  198. printf("add variable global volatile asignada:     0x%X\n", &varilo2);
  199.  
  200.  
  201. // El problema con la variable1 es que al haber usado 'extern' y no haberle
  202. // hecho una asignación de valor. el compilador entiende que se hace referencia
  203. // a una variable que está declarada en otra unidad de compilación.
  204. }
  205.  
  206. ////////////////////////////////////////////////////////////////////////////////////////////////
  207.  
  208. void Func8_Variables2(){
  209.  
  210. // Valores de inicio y lugar de almacenamiento de las variables
  211. //
  212.  
  213. putchar(10);
  214.  
  215. // Se crean y destruyen automáticamente (no se necesita especificar)
  216. auto int varbien1;
  217. auto int varbien2=0;
  218.  
  219. // Si es posible, se van a almacenar en algún registro del CPU para tener
  220. // un acceso más rápido a ellas. (Tamaño adecuado para entrar en un registro!)
  221. register int varbien3;
  222. register int varbien4=0;
  223.  
  224. printf("variable local auto sin asignar:      %d\n", varbien1);
  225. printf("variable local auto asignada:         %d\n", varbien2);
  226. printf("variable local register sin asignar:  %d\n", varbien3);
  227. printf("variable local register asignada:     %d\n", varbien4);
  228.  
  229. auto int var1 = 85;
  230. auto int var2 = var1;
  231. printf("var1: %d   add: 0x%X\n", var1, &var1);
  232. printf("var2: %d   add: 0x%X\n", var2, &var2);
  233.  
  234. register int var3 = 85;
  235. // Si estubiera en un registro no se obtendría una dirección de memoria!
  236. printf("var3: %d   add: 0x%X\n", var3, &var3);
  237.  
  238. register int i;
  239. // register int i=0;
  240. for(i=1; i<=10; i++){
  241. if(i==1) printf("add i: 0x%X\n",&i);
  242. printf("%d",i);
  243. }
  244. putchar(10);
  245. }
  246.  
  247. ////////////////////////////////////////////////////////////////////////////////////////////////
  248.  
  249. static void Func9_dummy1(register int* x){
  250.  
  251. printf("x: %d   add: 0x%X\n", *x, &x);
  252. }
  253.  
  254. ////////////////////////////////////////////////////////////////////////////////////////////////
  255.  
  256. static void Func10_dummy2(register int y){
  257.  
  258. printf("y: %d   add: 0x%X\n", y, &y);
  259. }
  260.  
  261. ////////////////////////////////////////////////////////////////////////////////////////////////
  262.  
  263. static void Func11_dummy3(volatile int z){
  264.  
  265. printf("z: %d   add: 0x%X\n", z, &z);
  266. }
  267.  
  268. ////////////////////////////////////////////////////////////////////////////////////////////////
  269. // Retorna un INT volatile, sólo se aplica al tipo de retorno.
  270.  
  271. volatile int Func12_dummy4(int arg){
  272.  
  273. int res = arg;
  274. return res;
  275. }
  276.  
  277. ////////////////////////////////////////////////////////////////////////////////////////////////
  278.  
  279. void Func13_Argumentos(){
  280.  
  281. putchar(10);
  282.  
  283. int a = 500;
  284. Func9_dummy1(&a);
  285.  
  286. int b = 1000;
  287. Func10_dummy2(b);
  288.  
  289. int c = 5000;
  290. Func10_dummy2(c);
  291.  
  292. int d = 100000;
  293. Func11_dummy3(d);
  294.  
  295. int e = Func12_dummy4(15);
  296. printf("%d\n", e);
  297. }
  298.  
  299. ////////////////////////////////////////////////////////////////////////////////////////////////
  300.  
  301. int main(){
  302.  
  303. Func4_MostrarCadenas1();
  304. Func5_MostrarMensajes1();
  305.  
  306. // Cualquiera de las 2 formas (con o sin extern, es lo mismo)
  307. extern void Test1_UnidadDeCompilacion1();
  308. extern void Test2_UnidadDeCompilacion1();
  309. extern void Test3_UnidadDeCompilacion1();
  310. extern void Test1_UnidadDeCompilacion2();
  311. extern void Test2_UnidadDeCompilacion2();
  312. void Test3_UnidadDeCompilacion2();
  313.  
  314. Test1_UnidadDeCompilacion1();
  315. Test2_UnidadDeCompilacion1();
  316. Test3_UnidadDeCompilacion1();
  317. Test1_UnidadDeCompilacion2();
  318. Test2_UnidadDeCompilacion2();
  319. Test3_UnidadDeCompilacion2();
  320.  
  321. Func8_Variables2();
  322.  
  323. Func3_StripReturn(cadenaCortada);
  324. printf("%s\n",cadenaCortada);
  325. system("pause");
  326. return (0);
  327. }
  328.  

unidad_comp1.cpp
Código
  1. //
  2. // By 85
  3. // elhacker.net
  4. // etalking.com.ar
  5. // boyscout_etk@hotmail.com
  6. // 2013
  7. //
  8.  
  9. ////////////////////////////////////////////////////////////////////////////////////////////////
  10.  
  11. #include<windows.h>
  12. #include<stdio.h>
  13.  
  14. #include "inclusiones.h"
  15.  
  16. ////////////////////////////////////////////////////////////////////////////////////////////////
  17.  
  18. int (*Ptr_Func1_StringCompare)(char*, char*);
  19.  
  20. ////////////////////////////////////////////////////////////////////////////////////////////////
  21.  
  22. extern void Test1_UnidadDeCompilacion1(){
  23.  
  24. // Los externs en este caso son locales a esta función.
  25. extern void Func6_getRAM(char* buf);
  26.  
  27. char TotalRAM[256] = "";
  28.        Func6_getRAM(TotalRAM);
  29. putchar(10);
  30.        printf("Test1_UnidadDeCompilacion1: Total RAM: %s\n", TotalRAM);
  31. }
  32.  
  33. ////////////////////////////////////////////////////////////////////////////////////////////////
  34.  
  35. extern void Test2_UnidadDeCompilacion1(){
  36.  
  37. // Los externs en este caso son locales a esta función.
  38. extern DWORD add_Func1_StringCompare;
  39. extern char cadena1[];
  40. extern char cadena2[];
  41. extern char cadena3[];
  42.  
  43. putchar(10);
  44.  
  45. Ptr_Func1_StringCompare = (int(*)(char*, char*))add_Func1_StringCompare;
  46.  
  47. //if(Func1_StringCompare(cadena1, cadena2) == 0)// No se puede!
  48. if(Ptr_Func1_StringCompare(cadena1, cadena2) == 0)
  49. {
  50. printf("Test2_UnidadDeCompilacion1: IGUALES\n");
  51. }
  52.  
  53. // No se puede! porque getRam no es un extern "global" en esta unidad de compilación.
  54. //char TotalRAM[256] = "";
  55.        //Func6_getRAM(TotalRAM);
  56.        //printf("Total RAM: %s\n", TotalRAM);
  57. }
  58.  
  59. ////////////////////////////////////////////////////////////////////////////////////////////////
  60.  
  61. extern void Test3_UnidadDeCompilacion1(){
  62.  
  63. // Cualquiera de las 2 formas
  64. extern void Func7_Variables1();
  65. void Func7_Variables1();
  66.  
  67. Func7_Variables1();
  68. }
  69.  

unidad_comp2.cpp
Código
  1. //
  2. // By 85
  3. // elhacker.net
  4. // etalking.com.ar
  5. // boyscout_etk@hotmail.com
  6. // 2013
  7. //
  8.  
  9. ////////////////////////////////////////////////////////////////////////////////////////////////
  10.  
  11. #include<windows.h>
  12. #include<stdio.h>
  13.  
  14. #include "inclusiones.h"
  15.  
  16. ////////////////////////////////////////////////////////////////////////////////////////////////
  17. // Los externs pueden ser globales para que sirvan en toda esta unidad de compilación
  18.  
  19. unsigned int (*Ptr_Func2_StringLength)(const char*);
  20.  
  21. extern DWORD add_Func2_StringLength;
  22. extern char cadena1[];
  23. extern char cadena2[];
  24. extern char cadena3[];
  25.  
  26. // Cualquiera de las 2 formas
  27. extern void Func13_Argumentos();
  28. void Func13_Argumentos();
  29.  
  30. ////////////////////////////////////////////////////////////////////////////////////////////////
  31.  
  32. extern void Test1_UnidadDeCompilacion2(){
  33.  
  34.  
  35. putchar(10);
  36.  
  37. //int len1 = Func2_StringLength(cadena1);// No se puede!
  38.  
  39. Ptr_Func2_StringLength = (unsigned int(*)(const char*))add_Func2_StringLength;
  40.  
  41. int len1 = Ptr_Func2_StringLength(cadena1);
  42.  
  43. printf("Test1_UnidadDeCompilacion2: len1: %d\n", len1);
  44. }
  45.  
  46.  
  47. ////////////////////////////////////////////////////////////////////////////////////////////////
  48.  
  49. extern void Test2_UnidadDeCompilacion2(){
  50.  
  51. // No se puede! Son 'inline' en otra unidad de compilación
  52. //Func4_MostrarCadenas1();
  53. //Func5_MostrarMensajes1();
  54. }
  55.  
  56. ////////////////////////////////////////////////////////////////////////////////////////////////
  57.  
  58. extern void Test3_UnidadDeCompilacion2(){
  59.  
  60. Func13_Argumentos();
  61. }
  62.  

inclusiones.h
Código
  1. //
  2. // By 85
  3. // elhacker.net
  4. // etalking.com.ar
  5. // boyscout_etk@hotmail.com
  6. // 2013
  7. //
  8.  
  9. ////////////////////////////////////////////////////////////////////////////////////////////////
  10.  
  11. #pragma once
  12.  
  13. ////////////////////////////////////////////////////////////////////////////////////////////////
  14. // En el archivo de inclusión no se especifica la clase de almacenamiento.
  15.  
  16. int Func1_StringCompare(char* q, char* a);
  17. unsigned int Func2_StringLength(const char* f);
  18. void Func3_StripReturn(char* str);
  19. void inline Func4_MostrarCadenas1();
  20. inline void Func5_MostrarMensajes1();
  21.  
  22.  


CODE
http://www.mediafire.com/?mzuaz5zxtttazut
112  Programación / Programación C/C++ / Re: Ayuda en Código de Snake en: 26 Marzo 2013, 22:08 pm
aparte para no ir en contra del concepto de 'modularidad' del programa
113  Programación / Programación C/C++ / Re: Ejecutar un bat... Al inicio de Windows en: 26 Marzo 2013, 22:01 pm
haber yo sólamente hice una búsqueda..
http://stackoverflow.com/questions/1154701/batch-cmd-adding-files-to-startup-list
http://superuser.com/questions/71190/running-bat-file-at-startup-as-administrator-in-windows-7
http://www.microloft.co.uk/startup.htm
http://www.tomshardware.com/forum/258456-45-autoloading-file-registry-startup
http://news.softpedia.com/news/How-To-Add-an-Application-To-Startup-Using-The-Registry-43488.shtml


y si te falta más código para trabajar con el registro te paso algunos códigos que tenía guardados.

Código
  1. // want to edit key "HKEY_LOCAL_MACHINE\Software\company name\game name\settings\value"
  2. // to "1" (DWORD)
  3.  
  4. void a(){
  5.  
  6. HKEY hkey;
  7. DWORD dwDisposition;
  8.  
  9. //ask for write permission KEY_WRITE
  10. if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,
  11.      TEXT("Software\\company name\\game name\\settings"),
  12.      0, NULL, 0,
  13.      KEY_WRITE, NULL,
  14.      &hkey, &dwDisposition) == ERROR_SUCCESS)
  15. {
  16. // etc..
  17. }
  18.  
  19. if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,
  20. TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, 0, NULL,
  21. &hkey, &dwDisposition) == ERROR_SUCCESS){
  22.  
  23. DWORD dwType, dwSize;
  24.    dwType = REG_DWORD;
  25.    dwSize = sizeof(DWORD);
  26.    DWORD rofl = 1;
  27.  
  28. // does not create anything
  29.    RegSetValueEx(hkey, TEXT("value"), 0, dwType, (PBYTE)&rofl, dwSize);
  30.    RegCloseKey(hkey);
  31. }
  32. }
  33.  
  34. LONG SetRegValue(const wchar_t* path,const wchar_t *name,const wchar_t *value)
  35. {
  36.    LONG status;
  37.    HKEY hKey;
  38.  
  39.    status = RegOpenKeyEx(HKEY_CURRENT_USER, (const char *)path, 0, KEY_ALL_ACCESS, &hKey);
  40.    if ( (status == ERROR_SUCCESS) && (hKey != NULL))
  41.    {
  42.        status = RegSetValueEx( hKey, (const char *)name, 0, REG_SZ, (BYTE*)value,
  43. ((DWORD)wcslen(value)+1)*sizeof(wchar_t));
  44.        RegCloseKey(hKey);
  45.    }
  46.    return status;
  47. }
  48.  

Código
  1. char cdkey[14] = "";
  2. void getCDKey()
  3. {
  4. HKEY  l_hKey;
  5.    DWORD l_dwBufLen = 17;
  6. DWORD type = REG_SZ;
  7.  
  8. DWORD l_ret = RegOpenKeyEx(
  9. HKEY_CURRENT_USER,
  10. "Software\\Ltfxhook",
  11. 0,KEY_QUERY_VALUE, &l_hKey);
  12. if(l_ret!=ERROR_SUCCESS)
  13. {
  14. Con_Echo("&rltfxkey retreival failed");
  15. }
  16. l_ret = RegQueryValueEx(l_hKey,"Key",NULL,&type,(LPBYTE)&cdkey,&l_dwBufLen);
  17. }
  18.  


Código
  1. char cdkey[14] = "";
  2. void getCDKey()
  3. {
  4. HKEY  l_hKey;
  5.    DWORD l_dwBufLen = 14;
  6. DWORD type = REG_SZ;
  7.  
  8. DWORD l_ret = RegOpenKeyEx(
  9. HKEY_CURRENT_USER,
  10. "Software\\Valve\\CounterStrike\\Settings",
  11. 0,KEY_QUERY_VALUE, &l_hKey);
  12. if(l_ret!=ERROR_SUCCESS)
  13. {
  14. DWORD l_ret = RegOpenKeyEx(
  15. HKEY_CURRENT_USER,
  16. "Software\\Valve\\Half-life\\Settings",
  17. 0,KEY_QUERY_VALUE, &l_hKey);
  18. if(l_ret!=ERROR_SUCCESS)
  19. return;
  20. }
  21. l_ret = RegQueryValueEx(l_hKey,"Key",NULL,&type,(LPBYTE)&cdkey,&l_dwBufLen);
  22. for(int i=0;i<13;i++)
  23. {
  24. switch( cdkey[i] )
  25. {
  26. case '0':
  27. cdkey[i] = 'g';
  28. break;
  29. case '1':
  30. cdkey[i] = 'a';
  31. break;
  32. case '2':
  33. cdkey[i] = 'u';
  34. break;
  35. case '3':
  36. cdkey[i] = 'l';
  37. break;
  38. case '4':
  39. cdkey[i] = 'x';
  40. break;
  41. case '5':
  42. cdkey[i] = 't';
  43. break;
  44. case '6':
  45. cdkey[i] = 'c';
  46. break;
  47. case '7':
  48. cdkey[i] = 'm';
  49. break;
  50. case '8':
  51. cdkey[i] = 'r';
  52. break;
  53. case '9':
  54. cdkey[i] = 'j';
  55. break;
  56. }
  57. }
  58. }
  59.  

Código
  1.  
  2. void printerr(DWORD dwerror) {
  3.  
  4. LPVOID lpMsgBuf;
  5.  
  6. FormatMessage(
  7.            FORMAT_MESSAGE_ALLOCATE_BUFFER |
  8.            FORMAT_MESSAGE_FROM_SYSTEM |
  9.            FORMAT_MESSAGE_IGNORE_INSERTS,
  10.            NULL,
  11.            dwerror,
  12.            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  13.            (LPTSTR) &lpMsgBuf,
  14.            0,
  15.            NULL
  16.    );
  17.  
  18. // Process any inserts in lpMsgBuf.
  19.    // ...
  20.    // Display the string.
  21.        if (isOut) {
  22.            fprintf(fout, "%s\n", lpMsgBuf);
  23.        } else {
  24.            printf("%s\n", lpMsgBuf);
  25.        }
  26.        // Free the buffer.
  27.        LocalFree(lpMsgBuf);
  28.    }
  29.  
  30.    bool regreadSZ(string& hkey, string& subkey, string& value, string& returnvalue, string& regValueType) {
  31.        char s[128000];
  32.        map<string,HKEY> keys;
  33.        keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT;
  34.        keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?
  35.        keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER;
  36.        keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE;
  37.        keys["HKEY_USERS"]=HKEY_USERS;
  38.        HKEY mykey;
  39.  
  40.        map<string,DWORD> valuetypes;
  41.        valuetypes["REG_SZ"]=REG_SZ;
  42.        valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ;
  43.        valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this.
  44.  
  45.        LONG retval=RegOpenKeyEx(
  46.            keys[hkey],         // handle to open key
  47.            subkey.c_str(),  // subkey name
  48.            0,   // reserved
  49.            KEY_READ, // security access mask
  50.            &mykey    // handle to open key
  51.        );
  52.        if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
  53.        DWORD slen=128000;
  54.        DWORD valuetype = valuetypes[regValueType];
  55.        retval=RegQueryValueEx(
  56.          mykey,            // handle to key
  57.          value.c_str(),  // value name
  58.          NULL,   // reserved
  59.          (LPDWORD) &valuetype,       // type buffer
  60.          (LPBYTE)s,        // data buffer
  61.          (LPDWORD) &slen      // size of data buffer
  62.        );
  63.        switch(retval) {
  64.            case ERROR_SUCCESS:
  65.                //if (isOut) {
  66.                //    fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
  67.                //} else {
  68.                //    printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
  69.                //}
  70.                break;
  71.            case ERROR_MORE_DATA:
  72.                //what do I do now?  data buffer is too small.
  73.                if (isOut) {
  74.                    fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
  75.                } else {
  76.                    printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
  77.                }
  78.                return false;
  79.            case ERROR_FILE_NOT_FOUND:
  80.                if (isOut) {
  81.                    fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
  82.                } else {
  83.                    printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
  84.                }
  85.                return false;
  86.            default:
  87.                if (isOut) {
  88.                    fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval);
  89.                } else {
  90.                    printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval);
  91.                }
  92.                return false;
  93.  
  94.        }
  95.        retval=RegCloseKey(mykey);
  96.        if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
  97.  
  98.        returnvalue = s;
  99.        return true;
  100.    }
  101.  


Código
  1.  
  2. HKEY hKey;
  3. LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
  4. bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
  5. bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
  6. std::wstring strValueOfBinDir;
  7. std::wstring strKeyDefaultValue;
  8. GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
  9. GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");
  10.  
  11. LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
  12. {
  13.    nValue = nDefaultValue;
  14.    DWORD dwBufferSize(sizeof(DWORD));
  15.    DWORD nResult(0);
  16.    LONG nError = ::RegQueryValueExW(hKey,
  17.        strValueName.c_str(),
  18.        0,
  19.        NULL,
  20.        reinterpret_cast<LPBYTE>(&nResult),
  21.        &dwBufferSize);
  22.    if (ERROR_SUCCESS == nError)
  23.    {
  24.        nValue = nResult;
  25.    }
  26.    return nError;
  27. }
  28.  
  29.  
  30. LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
  31. {
  32.    DWORD nDefValue((bDefaultValue) ? 1 : 0);
  33.    DWORD nResult(nDefValue);
  34.    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
  35.    if (ERROR_SUCCESS == nError)
  36.    {
  37.        bValue = (nResult != 0) ? true : false;
  38.    }
  39.    return nError;
  40. }
  41.  
  42.  
  43. LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
  44. {
  45.    strValue = strDefaultValue;
  46.    WCHAR szBuffer[512];
  47.    DWORD dwBufferSize = sizeof(szBuffer);
  48.    ULONG nError;
  49.    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
  50.    if (ERROR_SUCCESS == nError)
  51.    {
  52.        strValue = szBuffer;
  53.    }
  54.    return nError;
  55. }
  56.  

XD
114  Programación / Programación C/C++ / Re: Problema con struct en: 26 Marzo 2013, 21:56 pm
a veces no da error mientras no modifiques algo crítico, es decir si te salís fuera del límite de una cadena y escribís otra, en teoría no pasa nada. Pero si al pasarte fuera, terminás modificando la dirección almacenada de un puntero por ejemplo, entonces si sería una modificación crítica.

array[2] en teoría debería guardar 2 elementos que son array[0] y array[1], si usás [2] sería el tercero. aunque si no tira error debés estar modificando el dato que se encuentra a continuación, o a no ser que el compilador sea inteligente como para haber creado un array de 3.
115  Programación / Programación C/C++ / Re: Ayuda en Código de Snake en: 26 Marzo 2013, 21:30 pm
XD a secas

eso significa que intenta comprobar si tiene un valor distinto de 0, una comprobación de estado booleano. Pero si nunca es 0 entonces no tiene sentido comprobarlo.

a veces es muy útil por ejemplo para comprobar si un puntero fue asignado con una dirección de memoria.

int* pun = 0;//Asignar

if(pun){
}



116  Programación / Programación C/C++ / CRT personalizada en: 26 Marzo 2013, 16:21 pm
Hola, estaba leyendo este texto:
Citar
5) make your own CRT

   MUCH easier than you might think... what do you need from a runtime? to allocate/deallocate
   mem? to print to the console?

   look up the functions required to allocate memory from windows...

   now just have some functions that set needed globals:

   HANDLE g_hHeap = 0;

   extern "C" BOOL crt_initialize() { return (g_hHeap = HeapCreate(0, 0, 0))); }
   extern "C" BOOL crt_uninitialize() { return HeapDestroy(g_hHeap)); }

   you can now, if you choose, override the default CRT entry's name:

   extern "C" int mainCRTStartup()
   {
      crt_initialize();
      // maybe get the arguments here with GetCommandLine()
      main();//maybe send args here
      return 0;
   }

   so how do you do malloc()/free() ? how do you do new/delete? it's as simple as passing the
   requested sizes to the OS functions along with the heap handle made during the initialization

   extern "C" void * malloc(unsigned int size) { return HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, size); }
   extern "C" void free(void * p) { HeapFree(g_hHeap, 0, p); }

   void * __cdecl operator new(unsigned int size) { return HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, size); }
   void __cdecl operator delete(void *p) { HeapFree(g_hHeap, 0, p); }

   hopefully you can figure out the rest... especially how your crt entry should acquire and
   supply needed parameters to your main() or winmain()

6) bypass the normal CRT

   if you don't want to write a CRT, but also don't want the cruft that comes with the normal CRT,
   just specify that the linker should jump to your code first, NOT the crt

   /ENTRY:yourfunction

Y buscando información encontré algunas cosas interesantes, por ejemplo 2 proyectos de CRT propias, más que el otro estuve mirando el más reciente del 2010, que se llama 'minicrt'.
Me parece que les puede interesar a algunos, porque en el proyecto se puede encontrar el código de muchas implementaciones de funciones de C.
http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/e6f222d7-8e20-4d4a-8a6f-b72ade3661ac/
http://www.benshoof.org/blog/minicrt/
http://www.wheaty.net/
http://www.benshoof.org/blog/archive/
http://www.wheaty.net/downloads.htm

Se pueden encontrar versiones de las funciones originales que cumplen con los standards de C, hay implementaciones de algunas funciones que a mi por ejemplo me interesaban crear implementaciones personalizadas de ellas, atoi, strtok, y muchas otras

por ejemplo atoi
Código:
//==========================================
// minicrt - Chris Benshoof 2009
// atoi(), modified from
// http://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crt/atoi.c.htm
//==========================================
#include "libctiny.h"
 
extern "C" int __cdecl atoi(const char *String)
{
    int Value = 0, Digit;
    int c;
 
    while ((c = *String++) != '\0') {
 
        if (c >= '0' && c <= '9')
            Digit = (c - '0');
        else
            break;
 
        Value = (Value * 10) + Digit;
    }
 
    return Value;
}

aparte es un proyecto no tan antiguo, dice que es del 2010.
El otro si es del 2000.

saludos
117  Programación / Programación C/C++ / Re: ¿Me echáis un cable? en: 26 Marzo 2013, 14:41 pm
que raro porque los profesores son los que siempre dicen que no usés variables globales.
118  Programación / Programación C/C++ / Re: Dudas Punteros en: 26 Marzo 2013, 14:26 pm
por ejemplo, veamos esto
http://www.zator.com/Cpp/E2_2a.htm

Las variables pueden ser de diferentes tipos de datos, los punteros son variables pero de tipo puntero en sí, independientemente si fueron declaradas como CHAR, INT, etc.

Con referencia a las variables de tipo puntero, es tal como te dijeron.

Algo que también está permitido es hacer typecasting de variables normales para poder usarlas como punteros. Algo que yo llamo un "pseudopuntero" pero es tan sólo el uso del typecasting.

por ejemplo:

Código:
int entero1=5;
DWORD pseudopuntero = (DWORD)&entero1;
printf("entero1 %X\n", &entero1);
printf("pseudopuntero %X\n", pseudopuntero);
printf("pseudopuntero %d\n", *(int*)pseudopuntero);
system("pause");

Nótese que para un "pseudopuntero" se requiere tener en cuenta el tipo de dato correcto para guardar una dirección de memoria, y el tipo correcto de dato para mostrar el valor de la variable.
Es algo mucho más complicado por eso se prefiere usar variables de tipo puntero directamente, las cuales son las correctas para todo esto.
Cualquier cosa se puede ver otro ejemplo
http://foro.elhacker.net/programacion_cc/pseudopunteros-t385862.0.html






119  Programación / .NET (C#, VB.NET, ASP) / Steam_RCP: GUI parecida al Steam y conexión con BDD en: 24 Marzo 2013, 18:30 pm
Hola quería publicar el código fuente de un proyecto que había empezado a principios del año pasado (2012) y que presenté a modo de proyecto, en mi curso de programación .NET que estaba haciendo ese año.

El archivo Acerca.txt
Citar
Steam_RCP es un programa con interfáz gráfica que trata de
parecerse a la de la plataforma 'Steam'.

Se conecta a una base de datos SQL Server y permite
realizar operaciones con la base de datos.

Se trata de un sistema simple de gestión.
Fue hecho con fines educativos a modo de un proyecto de
estudiantes de programación .NET , a principios del 2012.

La idea de publicarlo es para aquellos que intenten hacer
algo parecido puedan usar este proyecto como una base.

Las funcionalidades de una interfáz se emularon en lo posible
de las mismas de Windows, ya que se anularon algunas del
sistema para recrearlas desde el programa.

Esta publicación no incluye el código SQL para la creación
de la base de datos, y no incluye el diagrama DER de la
base de datos.

Lo que se incluye es el código fuente completo de la aplicación,
el código fuente de un instalador, y los archivos de instalación.

Atte.
85

Me parece que puede ser de utilidad para personas que tengan que hacer proyectos similares, con conexión a base de datos SQL Server.

En la descarga se incluyen las cosas que dice en el archivo Acerca.txt.

En cuanto a la GUI, aparte de que tiene un parecido con la interfáz gráfica de la plataforma Steam, en realidad está copiada de la interfaz que tiene la aplicación de un amigo que también es usuario de este foro. Él había creado una excelente aplicación con GUI en C++, y ami me había gustado su diseño por lo que lo implementé en este programa, obviamente desde C#.

Acerca del programa, es como había dicho, un programa que realiza operaciones sobre una base de datos SQL Server.


http://img837.imageshack.us/img837/6297/steamrcp2.png
http://img163.imageshack.us/img163/2473/steamrcp3.png

Si quieren hacerlo arrancar directamente hacía el panel principal sin intentar cargar la base de datos, van a tener que comentar una parte del código dentro de :
Código:
private void Form1_Load(object sender, EventArgs e)
{
    ...

PROYECTO MSVC# 2010
http://www.mediafire.com/?uohce8xfi568fkw
120  Programación / Programación C/C++ / Re: Juego en OpenGL no se cierra Bien en: 24 Marzo 2013, 17:02 pm
recién voy a descargar tu src, no sabía que lo publicaste. cualquier cosa te mando pm.

Fijate estos programas básicos si te sirven de algo, más que nada lo que es la destrucción de la ventana. porque me dijiste por pm que la ventana se cerraba pero el proceso continuaba.
http://foro.elhacker.net/programacion_cc/ejemplo_winapi32_gui_conversor_decimal_a_binario-t358539.0.html
http://foro.elhacker.net/programacion_cc/ejemplo_de_programa_winapi32_gui-t358131.0.html

igual voy a mirar tu código ahora y cualquier cosa te mando un mp.

Páginas: 1 2 3 4 5 6 7 8 9 10 11 [12] 13 14 15 16 17 18 19 20 21
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines