Question

I have a function in my custom C library which returns a pointer to a float. (This is actually an array of floats which contains audio values).

I want to use this C library (and returned float array) in Unity3d so I am writing a C# wrapper for it. How do I properly import/declare my C function in my c# script?

my C declarations looks like this:

float*  getAudioBuffer(mySynth_t synth);

In C# my guess is that I should declared my imported function as returning float[] like this:

[DllImport (dll)]
private static extern float[]  getAudioBuffer(  IntPtr synth)

Is that correct? Shall I use ref keyword? Shall I use out keyword somewhere? I familiar with C++ but bot at all with C# so I do not really understand mashalling etc.

Also the data in the float array are audio data to fill Unity3d's audio buffer in OnFilterRead. So this will be called many times. Any hint, sample code, or pointer on best practices would be appreciated.

Was it helpful?

Solution

here is how I did it:

[DllImport (dll)]
private static extern IntPtr  getAudioBuffer(  IntPtr synth);

then to use it:

private float[] buffer = new float[1024];

void OnAudioFilterRead (float[] data, int channels)  
    {
         IntPtr buf = getAudioBuffer();

         Marshal.Copy(buf, buffer, 0, buffer.Length);
          int i, j;
           for ( i = 0, j=0; j < buffer.Length; i = i + channels, j++)
           { 
              data[i] = buffer[j];
              if (channels ==2)
                { data [i + 1] = data [i]; }
           }        
    }

Any hint on how to do it more efficiently would be welcome.

Some good reads: here, here and also here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top