Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Java, proyecto Panamá y cómo lidiar con el resultado de 'sugerencia' de Hunspell

Estoy experimentando con Hunspell y cómo interactuar con él usando Java Project Panama (Build 19-panama+1-13 (2022/1/18)). Pude hacer algunas pruebas iniciales, como crear un handle to Hunspell y luego usarlo para realizar una revisión ortográfica. Ahora estoy intentando algo más elaborado, dejando que Hunspell me dé suggestions para una palabra que no está presente en el diccionario. Este es el código que tengo para eso ahora:

 public class HelloHun { public static void main(String[] args) { MemoryAddress hunspellHandle = null; try (ResourceScope scope = ResourceScope.newConfinedScope()) { var allocator = SegmentAllocator.nativeAllocator(scope); // Point it to US english dictionary and (so called) affix file // Note #1: it is possible to add words to the dictionary if you like // Note #2: it is possible to have separate/individual dictionaries and affix files (eg per user/doc type) var en_US_aff = allocator.allocateUtf8String("/usr/share/hunspell/en_US.aff"); var en_US_dic = allocator.allocateUtf8String("/usr/share/hunspell/en_US.dic"); // Get a handle to the Hunspell shared library and load up the dictionary and affix hunspellHandle = Hunspell_create(en_US_aff, en_US_dic); // Feed it a wrong word var javaWord = "koing"; // Do a simple spell check of the word var word = allocator.allocateUtf8String(javaWord); var spellingResult = Hunspell_spell(hunspellHandle, word); System.out.println(String.format("%s is spelled %s", javaWord, (spellingResult == 0 ? "incorrect" : "correct"))); // Hunspell also supports giving suggestions for a word - which is what we do next // Note #3: by testing this `koing` word in isolation - we know that there are 4 alternatives for this word // Note #4: I'm still investigating how to access individual suggestions var suggestions = allocator.allocate(10); var suggestionCount = Hunspell_suggest(hunspellHandle, suggestions, word); System.out.println(String.format("There are %d suggestions for %s", suggestionCount, javaWord)); // `suggestions` - according to the hunspell API - is a `pointer to an array of strings pointer` // we know how many `strings` pointer there are, as that is the returned value from `suggest` // Question: how to process `suggestions` to get individual suggestions } finally { if (hunspellHandle != null) { Hunspell_destroy(hunspellHandle); } } } }

Lo que veo es que una llamada a Hunspell_suggest (creada a partir de jextract ) tiene éxito y me devuelve (4) sugerencias (que verifiqué usando Hunspell desde la línea de comandos), así que no hay problema.

Lo que es más desafiante para mí ahora es cómo desempaquetar el elemento de suggestions que regresa de esta llamada. He estado mirando varios ejemplos, pero ninguno de ellos parece entrar en este nivel de detalle (e incluso si encuentro ejemplos, parecen estar usando API de Panamá obsoletas).

Entonces, en esencia, aquí está mi pregunta:

¿Cómo descomprimo una estructura que, según se informa, consta de un puntero a una matriz de punteros de cadenas utilizando las API de Panamá JDK19 para su respectiva colección de cadenas?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mirando el encabezado aquí: https://github.com/hunspell/hunspell/blob/master/src/hunspell/hunspell.h#L80

 /* suggest(suggestions, word) - search suggestions * input: pointer to an array of strings pointer and the (bad) word * array of strings pointer (here *slst) may not be initialized * output: number of suggestions in string array, and suggestions in * a newly allocated array of strings (*slts will be NULL when number * of suggestion equals 0.) */ LIBHUNSPELL_DLL_EXPORTED int Hunspell_suggest(Hunhandle* pHunspell, char*** slst, const char* word);

El slst es un parámetro clásico de 'salida'. es decir, pasamos un puntero a algún valor (en este caso, un char** , es decir, una matriz de cadenas), y la función establecerá este puntero para nosotros, como una forma de devolver múltiples resultados. (siendo el primer resultado el número de sugerencias)

En Panamá, utiliza parámetros 'fuera' asignando un segmento con el diseño del tipo del que apunta el parámetro. En este caso, char*** es un puntero a char** , por lo que el diseño es ADDRESS . Luego pasamos el segmento creado a la función, y finalmente recuperamos/usamos el valor de ese segmento después de la llamada a la función, que habrá completado el contenido del segmento:

 // char*** var suggestionsRef = allocator.allocate(ValueLayout.ADDRESS); // allocate space for an address var suggestionCount = Hunspell_suggest(hunspellHandle, suggestionsRef, word); // char** (the value set by the function) MemoryAddress suggestions = suggestionsRef.get(ValueLayout.ADDRESS, 0);

Después de eso, puede iterar sobre la matriz de cadenas:

 for (int i = 0; i < suggestionCount; i++) { // char* (an element in the array) MemoryAddress suggestion = suggestions.getAtIndex(ValueLayout.ADDRESS, i); // read the string String javaSuggestion = suggestion.getUtf8String(suggestion, 0); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!