Marshling float* return value with PInvoke RRS feed

  • Question

  • I'm trying to use PInvoke to call a C++ function with the following signature:

    float *MyFunction();

    The return value in this case is a pointer to an array of 3 floats. Is there any way I can setup the MarshalAs attributes to allow me to use this function as though it returned a float[] in C#?

    This is what I have so far:

    [return: MarshalAs(UnmanagedType.LPArray,SizeConst=3)]
    public static extern float[] MyFunction();

    However it doesn't seem to work, I still get the usual "Cannot marshal 'return value': Invalid managed/unmanaged type combination." error when I try to call the function. I know I can change the return type to IntPtr but I'd rather not go that route if at all possible. MarshalAs(UnmanagedType.LPArray,SizeConst=XXX) works great for function parameters in some cases I've dealt with where C++ is calling my C# callbacks but it doesn't seem to work for the return value here.

    Does anyone know if it's possible to do this or am I out of luck?

    Thursday, November 12, 2009 3:47 AM


  • Hi,
    Here is a managed method signature for MyFunction, hope it can help:
        /// Return Type: float*
        [System.Runtime.InteropServices.DllImportAttribute("mydll.dll", EntryPoint="MyFunction")]
        public static extern  System.IntPtr MyFunction() ;


    Please remember to mark helpful replies as answers and unmark them if they provide no help.
    • Marked as answer by eryang Tuesday, November 17, 2009 6:44 AM
    Friday, November 13, 2009 10:20 AM