tags:

views:

109

answers:

1

c# struct defined as:

[StructLayout(LayoutKind.Sequential)]
    public struct RecognizeResult
    {
        /// float
        public float similarity;

        /// char*
        [MarshalAs(UnmanagedType.LPStr)]
        public string fileName;
    }

c function signature:
void FaceRecognition(RecognizeResult *similarity); //where similarity is a pointer to an array

P/Invoke signature:

 [DllImport(DllName, EntryPoint = "FaceRecognition")]
   public static extern void Recognize(ref RecognizeResult similarity);

this is how i call the c++ function in managed code:

RecognizeResult[] results = new RecognizeResult[100];
Recognize(ref results[0]); //through p/invoke

it turns out the array can't be passed to unmanaged code, only the first element is passed. how should i do to pass an array to unmanaged code (is it even possible)?

BTW, Do i have to pin the array when calling unmanaged code so that GC won't move the array?

+1  A: 

Try this:

[DllImport(DllName, EntryPoint = "FaceRecognition")]
public static extern void Recognize(RecognizeResult[] similarity);

RecognizeResult[] results = new RecognizeResult[100];
// fill array elements
Recognize(results);
Darin Dimitrov
it works, how stupid i am.
Benny
@Dimitrov, Do I need to Pin the array in case GC move the array?
Benny
It depends on what does the native function do with the pointer. If it stores it in some static variable that is used later by other native functions then yes, you need to pin the pointer, otherwise you should be ok.
Darin Dimitrov
thanks very much.
Benny