float* from C to C#

后端 未结 1 1277
不知归路
不知归路 2021-01-05 09:18

I\'m not truly a CS guy, so if any of you geniuses on here can point me in the right direction I\'ll be eternally grateful.

I have a c-code command line function tha

相关标签:
1条回答
  • 2021-01-05 10:09

    Use this signature for your C function (replace the mgrib.dll with 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 done, you can get the result like this:

    float[] result = new float[ size ];
    Marshal.Copy( pointer, result, 0, size );
    

    EDIT:

    Since the mgrib is allocating the memory using malloc, we need to free the memory using free function. However, you will have to wrap the call to free function in another function that will be exported from native library.

    extern "C" __declspec(dllexport) void mgrib_free( float* pointer );
    
    void mgrib_free( float* pointer )
    {
        free( result );
    }
    

    And then import it into like this:

    [DllImport( "mgrib.dll", EntryPoint = "mgrib_free",
                CallingConvention = CallingConvention.Cdecl )]
    public static extern void mgrib_free( IntPtr pointer );
    

    And invoke it as follows:

    mgrib_free( pointer );
    
    0 讨论(0)
提交回复
热议问题