- Home /
how to properly pass a float pointer from a C library to its C# wrapper
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[] aae_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. I read somewhere that there is a pinning process involved
Also the data in the float array are audio data that I want to copy to Unity3d's audio buffer in OnFilterRead. So this will be called many times. I read somewhere that there is a pinning process involved and I am not sure what to do of it.
Any hint, sample code, or pointer on best practices to get a float pointer (or float array) from C and pass it (or copy it if I have to) would be appreciated.
Answer by baba · Apr 16, 2014 at 11:44 PM
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.
O$$anonymous$$G This is exactly what Im looking for, Thanksss!!