How to use a C callback from C#?
<p>This is a .NET wrapper for the library <a href="http://www.mega-nerd.com/SRC/" rel="nofollow">Secret Rabbit Code (aka libsamplerate)</a>, when calling <strong>src_callback_read</strong> in <strong>CallbackRead</strong> : <em>AccessViolationException - Attempted to read or write protected memory</em>.</p>

<p>From C header :</p>

<pre><code>/* Opaque data type SRC_STATE. */
typedef struct SRC_STATE_tag SRC_STATE ;

typedef long (*src_callback_t) (void *cb_data, float **data) ;

SRC_STATE* src_callback_new (src_callback_t func, int converter_type, int channels,                 int *error, void* cb_data) ;

long src_callback_read (SRC_STATE *state, double src_ratio, long frames, float *
</code></pre>

<p>I then created the following :</p>

<p>C++/CLI class library that calls the C library :</p>

<pre><code>public delegate long SRCCallback ( void *cb_data, float **data ) ;

static  IntPtr CallbackNew ( SRCCallback ^func, RabbitConverter converter_type, int channels, int *error, void* cb_data )
        {
            src_callback_t* cb = ( src_callback_t* ) &amp;func;
            SRC_STATE* state =  src_callback_new ( *cb, ( int ) converter_type, channels, error, cb_data );
            IntPtr ptr = IntPtr ( state );
            return ptr;
        }

static long CallbackRead ( IntPtr  src_state, double src_ratio, long frames , float * data )
        {
            void* toPointer = src_state.ToPointer();
            SRC_STATE* state = ( SRC_STATE* ) toPointer;
            long l = src_callback_read ( state, src_ratio, frames, data );
            return l;
        }
</code></pre>

<p>C# application that uses the C++/CLI library :</p>

<pre><code>private static readonly unsafe SRCCallback _callback = target;

private static unsafe void Callback()
{
    var input = GetSine(1000.0d, 44100, 1);
    fixed (float* f = input)
    {
        RabbitError error = RabbitError.SRC_ERR_NO_ERROR;
        var @void = Rabbit.CallbackNew(_callback, RabbitConverter.SRC_SINC_BEST_QUALITY, 1, (int*) (&amp;error),
                                        (void*) IntPtr.Zero);
        var callbackRead = Rabbit.CallbackRead(@void  , 1d, input.Length/2, f);
        if (callbackRead != input.Length)
        {
            // throw new InvalidOperationException();
        }
    }
}

private static unsafe int target(void* cb_data, float** data)
{
    return 9;
}
</code></pre>
