# Error de despliegue de OcrInternals en aplicaciones x86
`IronTesseract.ReadScreenShot()` se ejecuta a través del pipeline AdvancedScan de IronOCR, que solo es compatible con un proceso Windows x64. Llamarlo desde una aplicación x86 falla con un error de implementación `OcrInternals`, incluso cuando el paquete `IronOcr.Extensions.AdvancedScan` está instalado.
```txt
Error while reading a screenshot, Error while deploying OcrInternals for IronOcr:
'Unable to locate 'OcrInternals' in
...\bin\Debug\runtimes\win-x86\native,
...\bin\Debug\runtimes\win.6.2-x86\native,
...\bin\Debug\runtimes\win.6-x86\native,
...\bin\Debug\,
...
nor in an embedded resource.'
Please install the NuGet Package 'IronOcr.Extension.AdvancedScan' when using IronOcr on Windows.
[Issue Code IRONOCR-OCRINTERNALS-DEPLOYMENT-ERROR-WIN]
```
La falla se presenta en la llamada `ReadScreenShot()` en sí:
```csharp
var ocr = new IronOcr.IronTesseract();
using (var input = new IronOcr.OcrInput())
{
input.LoadImage("Step_1-5.jpg");
var result = ocr.ReadScreenShot(input);
Console.WriteLine(result.Text);
}
```
Los componentes nativos de AdvancedScan de los que depende `ReadScreenShot()` no son compatibles dentro de un proceso x86. Se requiere instalar `IronOcr.Extensions.AdvancedScan`, pero no cambia la arquitectura del proceso anfitrión, por lo que la llamada aún no puede ejecutarse bajo x86.
[[e:(Instalar AdvancedScan no hace que ReadScreenShot() funcione en un proceso x86. El proceso que lo llama debe ejecutarse como x64.)]]
## Solución
### Opción 1: Apuntar a x64 directamente
La solución más limpia es cambiar el objetivo de la plataforma del proyecto a x64. En Visual Studio:
1. Haz clic derecho en el proyecto y selecciona **Propiedades**.
2. Abre la pestaña **Compilación**.
3. Configura **Objetivo de plataforma** en **x64**.
4. Desmarca **Preferir 32-bit**.
5. Reconstruir y ejecutar.
Con el proceso anfitrión ejecutándose como x64, `ReadScreenShot()` se ejecuta en un entorno compatible.
### Opción 2: Mantén la aplicación x86 y llama a un proceso auxiliar x64
Cuando la aplicación principal debe permanecer x86, mueve solo la operación OCR a un pequeño proceso auxiliar x64 y llámalo desde la aplicación existente. La estructura se ve así:
```txt
MainWinForms.x86
- .NET Framework Windows Forms app
- Platform target: x86
- Does not run ReadScreenShot() directly
- Calls the x64 helper process
OcrHelper.x64
- .NET Framework Console app
- Platform target: x64
- References IronOCR
- References IronOcr.Extensions.AdvancedScan
- Runs Ocr.ReadScreenShot()
- Returns the OCR result to the main app
```
La aplicación x86 permanece intacta mientras AdvancedScan se ejecuta donde es compatible.
#### Llamando al auxiliar desde la aplicación x86
Inicie el asistente con `ProcessStartInfo` y lea su salida:
```csharp
using System;
using System.Diagnostics;
using System.IO;
public static class OcrHelperClient
{
public static string ReadScreenshotWithHelper(string imagePath)
{
string helperExePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"OcrHelper.x64",
"OcrHelper.x64.exe"
);
if (!File.Exists(helperExePath))
{
throw new FileNotFoundException("The OCR helper executable was not found.", helperExePath);
}
var startInfo = new ProcessStartInfo
{
FileName = helperExePath,
Arguments = "\"" + imagePath + "\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (var process = new Process())
{
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("OCR helper failed: " + error);
}
return output;
}
}
}
```
Redirigir tanto `StandardOutput` como `StandardError` permite al llamador capturar el texto reconocido y mostrar cualquier falla del código de salida del asistente.
```csharp
string imagePath = @"C:\Images\Step_1-5.jpg";
string text = OcrHelperClient.ReadScreenshotWithHelper(imagePath);
Console.WriteLine(text);
```
#### Construyendo el auxiliar x64
Construya el asistente como una aplicación de consola x64 que haga referencia a `IronOcr` y `IronOcr.Extensions.AdvancedScan`. Lee la ruta de la imagen del primer argumento, ejecuta el OCR y escribe el resultado en @@--CODE-271@@:
```csharp
using System;
using System.IO;
using IronOcr;
namespace OcrHelper.x64
{
internal static class Program
{
private static int Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.Error.WriteLine("Missing image path argument.");
return 1;
}
string imagePath = args[0];
if (!File.Exists(imagePath))
{
Console.Error.WriteLine("Image file was not found: " + imagePath);
return 2;
}
string licenseKey = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY");
if (!string.IsNullOrWhiteSpace(licenseKey))
{
License.LicenseKey = licenseKey;
}
var ocr = new IronTesseract();
using (var input = new OcrInput())
{
input.LoadImage(imagePath);
var result = ocr.ReadScreenShot(input);
Console.WriteLine(result.Text);
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
return 99;
}
}
}
}
```
Códigos de salida distintos (`1`, `2`, `99`) permiten a la aplicación que llama distinguir un argumento faltante de un archivo faltante o una excepción inesperada.
## Notas para uso en producción
El ejemplo utiliza `stdout` por simplicidad. Para producción, elige el método de comunicación que se ajuste a tu arquitectura. Las opciones incluyen:
- Salida estándar y error estándar.
- Archivos JSON temporales.
- Tuberías nombradas.
- Un punto final HTTP local.
- Un servicio de Windows alojando la operación OCR x64.
**Para llamadas pequeñas o ocasionales:** lanzar el auxiliar bajo demanda suele ser suficiente. **Para cargas de trabajo de alto volumen:** un servicio auxiliar x64 que se ejecuta durante mucho tiempo tiende a ser más eficiente que generar un proceso por solicitud.
## Consejos para depuración
Realiza estas verificaciones cuando el enfoque del auxiliar se comporte mal:
- Confirme que la aplicación principal realmente necesita mantenerse en x86, y que `Ocr.Read()` no es suficiente para el escenario de captura de pantalla.
- Verifique que `ReadScreenShot()` tenga éxito cuando se ejecuta directamente desde un proceso x64.
- Construya el proyecto del asistente con **Objetivo de plataforma: x64**, y asegúrese de que la aplicación x86 nunca llame a `ReadScreenShot()` en sí misma.
- Instale `IronOcr.Extensions.AdvancedScan` en el proyecto del asistente x64.
- Comprueba que la ruta de la imagen pasada al auxiliar sea accesible por el proceso auxiliar.
- Configure la clave de licencia de IronOCR en código, configuración de la aplicación o la variable de entorno `IRONOCR_LICENSE_KEY`.
Al publicar el asistente, copie toda la salida de la compilación, no solo la `.exe`. La carpeta de salida debe incluir todas las bibliotecas referenciadas y los archivos de runtime nativos generados por la compilación, o el auxiliar encontrará el mismo error de despliegue.
IronTesseract.ReadScreenShot() se ejecuta a través del pipeline AdvancedScan de IronOCR, que solo es compatible con un proceso Windows x64. Llamarlo desde una aplicación x86 falla con un error de implementación OcrInternals, incluso cuando el paquete IronOcr.Extensions.AdvancedScan está instalado.
Error while reading a screenshot, Error while deploying OcrInternals for IronOcr:'Unable to locate 'OcrInternals' in...\bin\Debug\runtimes\win-x86\native,...\bin\Debug\runtimes\win.6.2-x86\native,...\bin\Debug\runtimes\win.6-x86\native,...\bin\Debug\,...nor in an embedded resource.'Please install the NuGet Package 'IronOcr.Extension.AdvancedScan' when using IronOcr on Windows.[Issue Code IRONOCR-OCRINTERNALS-DEPLOYMENT-ERROR-WIN]
Error while reading a screenshot, Error while deploying OcrInternals for IronOcr:
'Unable to locate 'OcrInternals' in
...\bin\Debug\runtimes\win-x86\native,
...\bin\Debug\runtimes\win.6.2-x86\native,
...\bin\Debug\runtimes\win.6-x86\native,
...\bin\Debug\,
...
nor in an embedded resource.'
Please install the NuGet Package 'IronOcr.Extension.AdvancedScan' when using IronOcr on Windows.
[Issue Code IRONOCR-OCRINTERNALS-DEPLOYMENT-ERROR-WIN]
Text
La falla se presenta en la llamada ReadScreenShot() en sí:
var ocr = new IronOcr.IronTesseract();using (var input = new IronOcr.OcrInput()){ input.LoadImage("Step_1-5.jpg"); var result = ocr.ReadScreenShot(input);Console.WriteLine(result.Text);}
var ocr = new IronOcr.IronTesseract();
using (var input = new IronOcr.OcrInput())
{
input.LoadImage("Step_1-5.jpg");
var result = ocr.ReadScreenShot(input);
Console.WriteLine(result.Text);
}
C#
Los componentes nativos de AdvancedScan de los que depende ReadScreenShot() no son compatibles dentro de un proceso x86. Se requiere instalar IronOcr.Extensions.AdvancedScan, pero no cambia la arquitectura del proceso anfitrión, por lo que la llamada aún no puede ejecutarse bajo x86.
Precaución: Instalar AdvancedScan no hace que ReadScreenShot() funcione en un proceso x86. El proceso que lo llama debe ejecutarse como x64.
Solución
Opción 1: Apuntar a x64 directamente
La solución más limpia es cambiar el objetivo de la plataforma del proyecto a x64. En Visual Studio:
Haz clic derecho en el proyecto y selecciona Propiedades.
Abre la pestaña Compilación.
Configura Objetivo de plataforma en x64.
Desmarca Preferir 32-bit.
Reconstruir y ejecutar.
Con el proceso anfitrión ejecutándose como x64, ReadScreenShot() se ejecuta en un entorno compatible.
Opción 2: Mantén la aplicación x86 y llama a un proceso auxiliar x64
Cuando la aplicación principal debe permanecer x86, mueve solo la operación OCR a un pequeño proceso auxiliar x64 y llámalo desde la aplicación existente. La estructura se ve así:
MainWinForms.x86 - .NET Framework Windows Forms app - Platform target: x86 - Does not run ReadScreenShot() directly - Calls the x64 helper processOcrHelper.x64 - .NET Framework Console app - Platform target: x64 - References IronOCR - References IronOcr.Extensions.AdvancedScan - Runs Ocr.ReadScreenShot() - Returns the OCR result to the main app
MainWinForms.x86
- .NET Framework Windows Forms app
- Platform target: x86
- Does not run ReadScreenShot() directly
- Calls the x64 helper process
OcrHelper.x64
- .NET Framework Console app
- Platform target: x64
- References IronOCR
- References IronOcr.Extensions.AdvancedScan
- Runs Ocr.ReadScreenShot()
- Returns the OCR result to the main app
Text
La aplicación x86 permanece intacta mientras AdvancedScan se ejecuta donde es compatible.
Llamando al auxiliar desde la aplicación x86
Inicie el asistente con ProcessStartInfo y lea su salida:
using System;using System.Diagnostics;using System.IO;public static class OcrHelperClient{ public static stringReadScreenshotWithHelper(string imagePath) { string helperExePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OcrHelper.x64", "OcrHelper.x64.exe" ); if (!File.Exists(helperExePath)) { throw new FileNotFoundException("The OCR helper executable was not found.", helperExePath); } var startInfo = new ProcessStartInfo {FileName = helperExePath,Arguments = "\"" + imagePath + "\"",UseShellExecute = false,RedirectStandardOutput = true,RedirectStandardError = true,CreateNoWindow = true }; using (var process = new Process()) { process.StartInfo = startInfo; process.Start(); string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { throw new Exception("OCR helper failed: " + error); } return output; } }}
using System;
using System.Diagnostics;
using System.IO;
public static class OcrHelperClient
{
public static string ReadScreenshotWithHelper(string imagePath)
{
string helperExePath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"OcrHelper.x64",
"OcrHelper.x64.exe"
);
if (!File.Exists(helperExePath))
{
throw new FileNotFoundException("The OCR helper executable was not found.", helperExePath);
}
var startInfo = new ProcessStartInfo
{
FileName = helperExePath,
Arguments = "\"" + imagePath + "\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (var process = new Process())
{
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("OCR helper failed: " + error);
}
return output;
}
}
}
C#
Redirigir tanto StandardOutput como StandardError permite al llamador capturar el texto reconocido y mostrar cualquier falla del código de salida del asistente.
string imagePath = @"C:\Images\Step_1-5.jpg";string text = OcrHelperClient.ReadScreenshotWithHelper(imagePath);Console.WriteLine(text);
string imagePath = @"C:\Images\Step_1-5.jpg";
string text = OcrHelperClient.ReadScreenshotWithHelper(imagePath);
Console.WriteLine(text);
C#
Construyendo el auxiliar x64
Construya el asistente como una aplicación de consola x64 que haga referencia a IronOcr y IronOcr.Extensions.AdvancedScan. Lee la ruta de la imagen del primer argumento, ejecuta el OCR y escribe el resultado en @@--CODE-271@@:
using System;using System.IO;using IronOcr;namespace OcrHelper.x64{ internal static class Program { private static intMain(string[] args) { try { if (args.Length == 0) {Console.Error.WriteLine("Missing image path argument."); return 1; } string imagePath = args[0]; if (!File.Exists(imagePath)) {Console.Error.WriteLine("Image file was not found: " + imagePath); return 2; } string licenseKey = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY"); if (!string.IsNullOrWhiteSpace(licenseKey)) {License.LicenseKey = licenseKey; } var ocr = new IronTesseract(); using (var input = new OcrInput()) { input.LoadImage(imagePath); var result = ocr.ReadScreenShot(input);Console.WriteLine(result.Text); } return 0; } catch (Exception ex) {Console.Error.WriteLine(ex.ToString()); return 99; } } }}
using System;
using System.IO;
using IronOcr;
namespace OcrHelper.x64
{
internal static class Program
{
private static int Main(string[] args)
{
try
{
if (args.Length == 0)
{
Console.Error.WriteLine("Missing image path argument.");
return 1;
}
string imagePath = args[0];
if (!File.Exists(imagePath))
{
Console.Error.WriteLine("Image file was not found: " + imagePath);
return 2;
}
string licenseKey = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY");
if (!string.IsNullOrWhiteSpace(licenseKey))
{
License.LicenseKey = licenseKey;
}
var ocr = new IronTesseract();
using (var input = new OcrInput())
{
input.LoadImage(imagePath);
var result = ocr.ReadScreenShot(input);
Console.WriteLine(result.Text);
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
return 99;
}
}
}
}
C#
Códigos de salida distintos (1, 2, 99) permiten a la aplicación que llama distinguir un argumento faltante de un archivo faltante o una excepción inesperada.
Notas para uso en producción
El ejemplo utiliza stdout por simplicidad. Para producción, elige el método de comunicación que se ajuste a tu arquitectura. Las opciones incluyen:
Salida estándar y error estándar.
Archivos JSON temporales.
Tuberías nombradas.
Un punto final HTTP local.
Un servicio de Windows alojando la operación OCR x64.
Para llamadas pequeñas o ocasionales: lanzar el auxiliar bajo demanda suele ser suficiente. Para cargas de trabajo de alto volumen: un servicio auxiliar x64 que se ejecuta durante mucho tiempo tiende a ser más eficiente que generar un proceso por solicitud.
Consejos para depuración
Realiza estas verificaciones cuando el enfoque del auxiliar se comporte mal:
Confirme que la aplicación principal realmente necesita mantenerse en x86, y que Ocr.Read() no es suficiente para el escenario de captura de pantalla.
Verifique que ReadScreenShot() tenga éxito cuando se ejecuta directamente desde un proceso x64.
Construya el proyecto del asistente con Objetivo de plataforma: x64, y asegúrese de que la aplicación x86 nunca llame a ReadScreenShot() en sí misma.
Instale IronOcr.Extensions.AdvancedScan en el proyecto del asistente x64.
Comprueba que la ruta de la imagen pasada al auxiliar sea accesible por el proceso auxiliar.
Configure la clave de licencia de IronOCR en código, configuración de la aplicación o la variable de entorno IRONOCR_LICENSE_KEY.
Al publicar el asistente, copie toda la salida de la compilación, no solo la .exe. La carpeta de salida debe incluir todas las bibliotecas referenciadas y los archivos de runtime nativos generados por la compilación, o el auxiliar encontrará el mismo error de despliegue.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.