Search code examples
javacjnaalsa

How to call ALSA allocation #define from JNA?


I am trying to use JNA to call ALSA library functions from Java. I have been successful calling the basic open/close APIs snd_pcm_open() and snd_pcm_close() so I know I have the library loading OK and the basics right.

The first thing my application needs to do with ALSA is call snd_pcm_hw_params_alloca() to allocate a hardware parameter structure. But this is defined in the C header file as a macro, not a symbol:

#define snd_pcm_hw_params_alloca(ptr) __snd_alloca(ptr, snd_pcm_hw_params)

For a C application it would be called like this:

snd_pcm_hw_params_t *params;
snd_pcm_hw_params_alloca(&params);

and "params" is then passed to many subsequent API calls.

I am not much of a C expert, I cannot figure out exactly what this is doing. I expected a memory allocation of a structure, but the next line in the header file defines snd_pcm_hw_params like:

int snd_pcm_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t *params);

So does that mean the macro is returning a pointer to a function? How can I model this in JPA?


Solution

  • This function returns a pointer to a structure whose definition you do not know. (This is why you need all those accessor functions.)

    alloca() allocates memory from the stack, which implies that it's freed as soon as the current function returns. This means that you cannot wrap this into a function to be called from Java.

    Instead of snd_pcm_hw_params_alloca(), use snd_pcm_hw_params_malloc(), and don't forget to call snd_pcm_hw_params_free() at the correct time.