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?

2
  • How does your P/Invoke function declaration look like in C#? In particular, how do you marshal the argument? Commented Nov 10, 2009 at 7:22
  • @Rudolph, I don't know how to marshal the array. Commented Nov 10, 2009 at 7:28

1 Answer 1

1

Try this:

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

RecognizeResult[] results = new RecognizeResult[100];
// fill array elements
Recognize(results);
Sign up to request clarification or add additional context in comments.

2 Comments

@Dimitrov, Do I need to Pin the array in case GC move the array?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.