Use this signature for your C function (replace mgrib.dll with the real library name).
[DllImport( "mgrib.dll", EntryPoint = "mgrib" )] public static extern IntPtr mgrib( int argc, [MarshalAs( UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr )] StringBuilder[] argv );
Call the mgrib function as follows:
// Prepare arguments in proper manner int argc = 0; StringBuilder[] argv = new StringBuilder[ argc ]; IntPtr pointer = mgrib( argc, argv );
When the call is completed, you can get the result as follows:
float[] result = new float[ size ]; Marshal.Copy( pointer, result, 0, size );
EDIT
Since mgrib allocates memory using malloc , we need to free memory using the free function. However, you will have to transfer the call to the free function to another function that will be exported from the native library.
extern "C" __declspec(dllexport) void mgrib_free( float* pointer ); void mgrib_free( float* pointer ) { free( result ); }
And then import it like this:
[DllImport( "mgrib.dll", EntryPoint = "mgrib_free", CallingConvention = CallingConvention.Cdecl )] public static extern void mgrib_free( IntPtr pointer );
And call it like this:
mgrib_free( pointer );
Rest wing
source share