Search code examples
c#functionpinvokedeclarationunmanaged

How to correctly declare unmanaged DLL function?


I'm trying to call an unmanaged DLL's function in my C# app. The function declaration is this. The function writes to file the data from an acquisition board (i.e., from arrays real_data and imag_data).

I'm using the following declaration, but the file contains incorrect data and I think that the declaration is wrong:

[DllImport(@"C:\SpinCore\SpinAPI\lib32\spinapi.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int pb_write_ascii_verbose(string fname, int num_points, float SW, float SF, ref int[] real_data, ref int[] imag_data);

Usage:

pb_write_ascii_verbose(@"C:\Users\Public\direct_data_0.txt", numberOfPoints, (float)actualSW, (float)sequence.Frequency, ref idata, ref idata_imag);

Is this correctly declared? If so, what is the proper declaration?


Solution

  • You need to give Interop a hint to marshal the arrays as LPArray. ref is not required in this case:

    [DllImport(@"C:\SpinCore\SpinAPI\lib32\spinapi.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int pb_write_ascii_verbose(
        string fname, 
        int num_points, 
        float SW, 
        float SF, 
        [MarshalAs(UnmanagedType.LPArray)]
        int[] real_data, 
        [MarshalAs(UnmanagedType.LPArray)]
        int[] imag_data);