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


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 261
371  Programación / Programación C/C++ / Re: Leer dll en consola win32 en: 18 Junio 2020, 14:23 pm
Da problemas como puse arriba.

Lo que quiero, para dejarlo más claro. Creé una dll de C++ nativo o win32.

Código
  1. #include "pch.h"
  2. #include "Super_dll.h"
  3.  
  4. extern "C" {
  5. __declspec(dllexport) int WINAPI Suma(int, int);
  6. __declspec(dllexport) LPTSTR WINAPI Mensaje();
  7. };
  8.  
  9. // Suma.
  10. int WINAPI Suma(int a, int b) { return a + b; }
  11.  
  12. // Mensaje.
  13. LPTSTR WINAPI Mensaje() { return LPTSTR(L"Hola. Soy una DLL Win32 escrito en C++."); }

Físicamente el archivo se llama Super_dll.dll.

En el mismo proyecto creo otro como es en este caso en C#.
Código
  1. using System;
  2. using System.Runtime.InteropServices;
  3.  
  4. namespace Consola_02_cs
  5. {
  6.    class Program
  7.    {
  8.        // Importar dll.
  9.        [DllImport("Super_dll.dll")]
  10.        extern static public int Suma(int a, int b);
  11.        [DllImport("Super_dll.dll")]
  12.        extern static public IntPtr Mensaje();
  13.  
  14.        static void Main()
  15.        {
  16.            // Título de la ventana.
  17.            Console.Title = "Consola C# 2019";
  18.  
  19.            // Tamaño de la ventana.
  20.            Console.SetWindowSize(40, 5);
  21.  
  22.            // Color de las letras.
  23.            Console.ForegroundColor = ConsoleColor.Green;
  24.  
  25.            Console.WriteLine(Marshal.PtrToStringAuto(Mensaje()));
  26.            Console.WriteLine(Suma(1764, -764).ToString());
  27.  
  28.            // Pulse cualquier tecla para salir.
  29.            Console.ReadKey();
  30.        }
  31.    }
  32. }

Me lee la dll como muestra abajo de ejemplo.


La interfaz hecho con la consola de C# ha leído la dll hecho con C++ nativo o win32.

Quiero hacer exactamente lo mismo, la dll es la misma, y está el archivo Super_dll.dll al lado del ejecutable. En este caso, la interfaz en vez de ser en C#, lo quiero hacer en consola en C++ nativo o win32.

Hice pruebas hasta con VB .net de la interfaz leyendo la dll y funciona.
Código:
Imports System.Runtime.InteropServices
Module Module1

    Sub Main()
        ' Título de la ventgana.
        Console.Title = "Consola VB 2019"

        ' Tamaño de la ventana.
        Console.SetWindowSize(40, 5)

        ' Color de las letras.
        Console.ForegroundColor = ConsoleColor.Cyan

        Console.WriteLine(Marshal.PtrToStringAuto(SUPER_DLL.Mensaje()))
        Console.WriteLine(SUPER_DLL.Suma(1764, -764).ToString())

        ' Pulse cualquier tecla para salir.
        Console.ReadKey()
    End Sub

    Friend Class SUPER_DLL
        <DllImport("Super_dll.dll")>
        Public Shared Function Suma(ByVal a As Integer, ByVal b As Integer) As Integer

        End Function
        <DllImport("Super_dll.dll")>
        Public Shared Function Mensaje() As IntPtr

        End Function
    End Class

End Module

La interfaz en C++ se me resiste tal como la quiero.

Lo curioso, haciendo pruebas con la interfaz en C++ del CLR o .net, también me da quebraderos de cabeza.
Código
  1. #include "pch.h"
  2.  
  3. using namespace System;
  4.  
  5.    [DllImport("Super_dll.dll")]
  6.    extern int Suma(int a, int b);
  7.    [DllImport("Super_dll.dll")]
  8.    extern IntPtr Mensaje();
  9.  
  10.  
  11. int main(array<System::String ^> ^args)
  12. {
  13.    // T&#237;tulo de la ventana.
  14.    Console::Title = "Consola C++ CLR 2019";
  15.  
  16.    // Tama&#241;o de la ventana.
  17.    Console::SetWindowSize(40, 5);
  18.  
  19.    // Color de las letras.
  20.    Console::ForegroundColor = ConsoleColor::Yellow;
  21.  
  22.    Console::WriteLine(Mensaje());
  23.    Console::WriteLine(Suma(1764, -764).ToString());
  24.  
  25.    // Pulse cualquier tecla para salir.
  26.    Console::ReadKey();
  27.    return 0;
  28. }
  29.  

Errores.
Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido
Error   C2337   'DllImport': no se encontró el atributo   Consola_clr_cpp   C:\Users\Usuario\Documents\Visual Studio 2019\Projects\Super_DLL\Consola_clr_cpp\Consola_clr_cpp.cpp   7   


;)
372  Programación / Programación C/C++ / Re: Leer dll en consola win32 en: 18 Junio 2020, 13:29 pm
Por lo que te he entendido, parece que es algo así.

Código
  1. #include <iostream>
  2. #include <windows.h>
  3.  
  4. extern "C"
  5. {
  6.    int WINAPI Suma(int a, int b);
  7.    LPTSTR WINAPI Mensaje();
  8. };
  9.  
  10. int main()
  11. {
  12.    std::cout << Mensaje();
  13.    std::cout << Suma(1764, -764);
  14.  
  15.    // Esperando pulsar Enter para salir.
  16.    std::cin.get();
  17.    return 0;
  18. }
373  Programación / Programación C/C++ / Re: Leer dll en consola win32 en: 18 Junio 2020, 12:52 pm
Sigo pescando...

Parece ser que la primera opción es más cómodo por decirlo de alguna manera.

¿Este código de abajo lo pongo en un archivo en cabecera llamado Consola_win32_cpp.h?

Código
  1. extern "C"
  2. {
  3. int WINAPI Suma(int a, int b);
  4. LPTSTR WINAPI Mensaje();
  5. };

¿Y en el archivo Consola_win32_cpp.cpp este otro?
Código
  1. #include <iostream>
  2. #include <windows.h>
  3.  
  4. int main()
  5. {
  6.    std::cout << Marshal.PtrToStringAuto(SUPER_DLL.Mensaje());
  7.    std::cout << SUPER_DLL.Suma(1764, -764).ToString();
  8.  
  9.    // Esperando pulsar Enter para salir.
  10.    std::cin.get();
  11.    return 0;
  12. }

No me sale.

Y sin cabecera lo he intentado hacerlo así:
Código
  1. #include <iostream>
  2. #include <windows.h>
  3.  
  4. int main()
  5. {
  6.    std::cout << Marshal->PtrToStringAuto(C->Mensaje());
  7.    std::cout << C->Suma(1764, -764)->ToString();
  8.  
  9.    // Esperando pulsar Enter para salir.
  10.    std::cin.get();
  11.    return 0;
  12. }
  13.  
  14. extern "C"
  15. {
  16.    int WINAPI Suma(int a, int b);
  17.    LPTSTR WINAPI Mensaje();
  18. };

Tampoco funciona.
374  Programación / Programación C/C++ / Leer dll en consola win32 en: 18 Junio 2020, 10:27 am
Buenas:

Tengo un ejemplo en C# para leer una dll hecho en C++ Win32.

Código C#:

Código
  1. using System;
  2. using System.Runtime.InteropServices;
  3.  
  4. namespace Consola_cs
  5. {
  6.    class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.            Console.WriteLine(Marshal.PtrToStringAuto(SUPER_DLL.Mensaje()));
  11.            Console.WriteLine(SUPER_DLL.Suma(1764, -764).ToString());
  12.  
  13.            // Pulse cualquier tecla para salir.
  14.            Console.ReadKey();
  15.        }
  16.        internal class SUPER_DLL
  17.        {
  18.            [DllImport("Super_dll.dll")]
  19.            extern static public int Suma(int a, int b);
  20.            [DllImport("Super_dll.dll")]
  21.            extern static public IntPtr Mensaje();
  22.        }
  23.    }
  24. }


Quiero adaptarlo la consola en Win32, pero me da errores.

Código C++ Win32:

Código
  1. #include <iostream>
  2. #include <windows.h>
  3.  
  4. int main()
  5. {
  6.    std::cout << Marshal.PtrToStringAuto(SUPER_DLL.Mensaje());
  7.    std::cout << SUPER_DLL.Suma(1764, -764).ToString();
  8.  
  9.    // Esperando pulsar Enter para salir.
  10.    std::cin.get();
  11.    return 0;
  12. }
  13.  
  14. internal class SUPER_DLL
  15. {
  16.    [DllImport("Super_dll.dll")]
  17.    extern static public int Suma(int a, int b);
  18.    [DllImport("Super_dll.dll")]
  19.    extern static public IntPtr Mensaje();
  20. }
  21.  
Documento de aquí.


¿Alguna idea?

Saludos.
375  Programación / Scripting / Re: Probando este código en: 17 Junio 2020, 21:17 pm
Lo he instalado ahora y lo he cambiado.



Me sale con otro error.

Citar
Can't find a usable init.tcl in the following directories:
    C:/Python27/lib/tcl8.5 {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/Python_consola_01/env1/lib/tcl8.5} {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/Python_consola_01/lib/tcl8.5} {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/Python_consola_01/env1/library} {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/Python_consola_01/library} {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/Python_consola_01/tcl8.5.15/library} {C:/Users/Meta/Documents/Visual Studio 2019/Projects/Python_consola_01/tcl8.5.15/library}



This probably means that Tcl wasn't installed properly.

Precisamente en la primera línea.

root = Tkinter.Tk()
376  Programación / .NET (C#, VB.NET, ASP) / Re: Corregir este programa en: 17 Junio 2020, 19:54 pm
Editado el primer post, que me olvidé de poner el código completo.
377  Programación / .NET (C#, VB.NET, ASP) / Corregir este programa en: 17 Junio 2020, 16:43 pm
Buenas gente del foro:

Teniendo este programa, no se comporta como quiero. Se trata de usar solo las teclas flechas y la tecla Enter. Con ello se puede crear un nombre, escribir un nombre que quiera. Cuando ya termine, pulso Enter y se posiciona en la parte indicada en la imagen de abajo.

Aquí abajo, escribí todo a AAAAAAAAAAAAA.

Al pulsar Enter, tiene que ser capaz de señalar con las teclas flechas izquiera y derecha para poder elegir ATRÁS o GUARDAR.


Una vez que haya elegido con el símbolo en > ATRÁS, si pulsa Enter muestra un mensaje:
Código
  1. Console.Write("HAS PULSADO ATRÁS   ");

El programa en esta parte se acaba ahí.

Si con las flechas del teclado selecciona en > GUARDAR, luego pulsa la tecla Enter. A parte que el nombre como en este caso AAAAAAAAAAA, se almacena en la variable...
Código
  1. static string guardarNombre = "";

Muestra el mensaje: HAS GUARDADO y el nombre AAAAAAAAAAAAAAAA en pantalla.

Código completo en C#:
Código
  1. using System;
  2.  
  3. namespace LCD_nombre_archivo_consola_06
  4. {
  5.    class Program
  6.    {
  7.        static string guardarNombre = "";
  8.        static int coordenadaX = 0;
  9.        static ConsoleKey key;
  10.  
  11.        static readonly char[] roALFANUMERICO = new char[] {
  12.            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P',
  13.            'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  14.            'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y',
  15.            'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','.', ',', '-', '_', ':', ';',
  16.            '¿', '?', '(', ')', '[', ']', '{', '}','=', '$','&', '"', ' '};
  17.  
  18.        static readonly int[] roINDICE_ARRAY = new int[] {
  19.            80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80 };
  20.  
  21.        private static readonly string[] roTEXTO = new string[] { "ATRÁS", "GUARDAR" };
  22.  
  23.        static int index = 0;
  24.        static void Main(string[] args)
  25.        {
  26.            // Título de la pantalla.
  27.            Console.Title = "Cambiar nombre";
  28.  
  29.            Inicio();
  30.        }
  31.  
  32.        #region Inico.
  33.        private static void Inicio()
  34.        {
  35.            // Tamaño de la ventana.
  36.            Console.SetWindowSize(20, 5);
  37.  
  38.            // Fondo verde.
  39.            Console.BackgroundColor = ConsoleColor.Blue;
  40.  
  41.            // Letras negras.
  42.            Console.ForegroundColor = ConsoleColor.White;
  43.  
  44.            // Limpiar pantalla.
  45.            Console.Clear();
  46.  
  47.            Console.SetCursorPosition(0, 0);
  48.            Console.Write("Nombre del relé 1:  ");
  49.            Console.SetCursorPosition(0, 1);
  50.            //Console.Write("AAAAAAAAAAAAAAAA");
  51.  
  52.            // Recorre todo el índice del array y el de los datos alfanumérico.
  53.            for (int i = 0; i < roINDICE_ARRAY.Length; i++)
  54.            {
  55.                Console.Write(roALFANUMERICO[roINDICE_ARRAY[i]]);
  56.            }
  57.  
  58.            Console.SetCursorPosition(2, 3);
  59.            Console.Write(roTEXTO[0]); // ATRÁS.
  60.            Console.SetCursorPosition(12, 3);
  61.            Console.Write(roTEXTO[1]); // GUARDAR.
  62.  
  63.            while (true)
  64.            {
  65.                Console.SetCursorPosition(coordenadaX, 1);
  66.                key = Console.ReadKey(true).Key;
  67.                switch (key)
  68.                {
  69.                    case ConsoleKey.RightArrow:
  70.                        if (coordenadaX < 15)
  71.                            coordenadaX++;
  72.                        break;
  73.  
  74.                    case ConsoleKey.LeftArrow:
  75.                        if (coordenadaX > 0)
  76.                            coordenadaX--;
  77.                        break;
  78.  
  79.                    case ConsoleKey.UpArrow:
  80.                        roINDICE_ARRAY[coordenadaX]++;
  81.                        if (roINDICE_ARRAY[coordenadaX] >= roALFANUMERICO.Length)
  82.                        {
  83.                            roINDICE_ARRAY[coordenadaX] = 0;
  84.                        }
  85.                        Console.Write(roALFANUMERICO[roINDICE_ARRAY[coordenadaX]]);
  86.                        break;
  87.  
  88.                    case ConsoleKey.DownArrow:
  89.                        roINDICE_ARRAY[coordenadaX]--;
  90.                        if (roINDICE_ARRAY[coordenadaX] < 0)
  91.                        {
  92.                            roINDICE_ARRAY[coordenadaX] = roALFANUMERICO.Length - 1;
  93.                        }
  94.                        Console.Write(roALFANUMERICO[roINDICE_ARRAY[coordenadaX]]);
  95.                        break;
  96.  
  97.                    case ConsoleKey.Enter:
  98.                        Console.SetCursorPosition(1, 3);
  99.                        Console.Write(">");
  100.  
  101.                        while (true)
  102.                        {
  103.                            key = Console.ReadKey(true).Key;
  104.  
  105.                            switch (key)
  106.                            {
  107.                                case ConsoleKey.RightArrow:
  108.                                case ConsoleKey.LeftArrow:
  109.                                    index = 1 - index;
  110.                                    break;
  111.  
  112.                                case ConsoleKey.UpArrow:
  113.                                case ConsoleKey.DownArrow:
  114.                                    Console.SetCursorPosition(coordenadaX, 1);
  115.                                    break;
  116.  
  117.                                case ConsoleKey.Enter:
  118.  
  119.                                    break;
  120.                            }
  121.  
  122.                            for (int a = 0; a < 2; a++)
  123.                            {
  124.                                Console.SetCursorPosition(1 + (10 * a), 3);
  125.                                if (a == index)
  126.                                    Console.Write(">");
  127.                                else
  128.                                    Console.Write(" ");
  129.                            }
  130.  
  131.                            if (index == 0)  // se pulsó Atrás
  132.                            {
  133.                                Atras();
  134.                                //break;  // vuelve a la edición de letras
  135.                            }
  136.  
  137.                            if (index == 1)  // se pulsó Guardar
  138.                            {
  139.                                Guardar();
  140.                            }
  141.                        }
  142.                }
  143.            }
  144.        }
  145.        #endregion
  146.  
  147.        private static void Atras()
  148.        {
  149.            Console.Clear();
  150.            Console.SetCursorPosition(0, 1);
  151.            Console.Write("HAS PULSADO ATRÁS   ");
  152.            Console.ReadKey(); // Pulse cualquier tecla para salir.
  153.        }
  154.  
  155.        private static void Guardar()
  156.        {
  157.            Console.Clear();
  158.            Console.SetCursorPosition(0, 1);
  159.            Console.Write("HAS GUARDADO       ");
  160.            for (int a = 0; a < roINDICE_ARRAY.Length; a++)
  161.            {
  162.                guardarNombre += roALFANUMERICO[roINDICE_ARRAY[a]].ToString();
  163.            }
  164.            Console.SetCursorPosition(0, 2);
  165.            Console.Write(guardarNombre);
  166.        }
  167.    }
  168. }

¿Alguna idea?

Un saludo.
378  Programación / Scripting / Probando este código en: 17 Junio 2020, 15:55 pm
Buenas:

Tengo este código de Python 2.x. No me funciona en Visual Studio Community 2019 (Gratuito).

Código
  1. import os, sys, tkFileDialog,Tkinter
  2.  
  3. root = Tkinter.Tk()
  4. root.withdraw()
  5.  
  6. formats = [ ('Roms Super Nintendo SMC','.smc'),('Roms Super Nintendo SFC','.sfc'),('Fichier Bin','.bin'),('Roms Super Nintendo','.smc .sfc .bin') ]
  7.  
  8. input = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=formats,title='Select file to swap bin HI to LO like A16->A15, A17->A16...A21->A20 and A15->21')
  9. if not input:
  10.        print "Error: Cannot open file"
  11.        sys.exit()
  12.  
  13. output = tkFileDialog.asksaveasfile(parent=root,mode='wb',filetypes=formats,title='Create output file name')
  14. if not output:
  15.        print "Error: cannot create output file"
  16.        sys.exit()
  17.  
  18.  
  19. # reading input file to a byte array
  20. data = bytearray(input.read())
  21.  
  22. # calculating rom size in 2 exponants
  23. expsize = 0
  24. bytesize = len(data)
  25. while bytesize > 1:
  26.        expsize += 1
  27.        bytesize = bytesize // 2
  28.  
  29. # init a proper size empty bytearray
  30. buffer = bytearray()
  31. for i in range(2**expsize): buffer.append(0)
  32.  
  33. # let's do the swap
  34. count = 0
  35. for i in range(len(data)):
  36.        addr = (i & 0x7fff) + ((i & 0x008000) << (expsize - 16)) + ((i & 0x010000) >> 1) + ((i & 0x020000) >> 1) + ((i & 0x040000) >> 1) + ((i & 0x080000) >> 1) + ((i & 0x100000) >> 1) + ((i & 0x200000) >> 1)
  37.        if addr != i: count += 1
  38.        buffer[addr] = data[i]
  39. print "Swapped %s (%s) addresses" % (count, hex(count))
  40.  
  41. # writing output file
  42. output.write(buffer)
  43.  
  44. # close file handles
  45. input.close()
  46. output.close()

Me sale estos errores.
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy\__main__.py", line 45, in <module>
    cli.main()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 429, in main
    run()
  File "c:\program files (x86)\microsoft visual studio\2019\community\common7\ide\extensions\microsoft\python\core\debugpy/..\debugpy\server\cli.py", line 266, in run_file
    runpy.run_path(options.target, run_name=compat.force_str("__main__"))
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 261, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\runpy.py", line 236, in _get_code_from_file
    code = compile(f.read(), fname, 'exec')
  File "C:\Users\Meta\Documents\Visual Studio 2019\Python_consola_01\Python_consola_01\Python_consola_01.py", line 10
    print "Error: Cannot open file"
                                  ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Error: Cannot open file")?
Press any key to continue . . .

¿Les dicen algo?

Saludos.
379  Programación / Programación C/C++ / Re: Capturar tecla en: 16 Junio 2020, 22:26 pm
ReadConsole.

Todo sobre consola de texto en Windows: https://docs.microsoft.com/en-us/windows/console/

Muchas gracias.
380  Programación / Programación C/C++ / Capturar tecla en: 16 Junio 2020, 13:49 pm
Buenas:

En C++ CLR para almacenar en una variable cualquier tecla pulsada de hace así indicado abajo.
Código:
 
// Almacena la tecla pulsada en la variable.
ConsoleKey teclaInicial;

¿Cómo se hace en C++ Win32?

Saludos.
Páginas: 1 ... 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 [38] 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ... 261
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines