3

I have an application in which I need to pass an array from C# to a C++ DLL. What is the best method to do it? I did some search on Internet and figured out that I need to pass the arrays from C# using ref. The code for the same:

status = IterateCL(ref input, ref output);

The input and output arrays are of length 20. and the corresponding code in C++ DLL is

IterateCL(int *&inArray, int *&outArray)

This works fine for once. But if I try to call the function from C# in a loop the second time, the input array in C# is showing up as an array of one element. Why is this happening and please help me how I can call this function iteratively from C#.

Thanks, Rakesh.

2 Answers 2

2

You need to use:

[DllImport("your_dll")]
public extern void IterateCL([In, MarshalAs(UnmanagedType.LPArray)] int[] arr1, [Out, MarshalAs(UnmanagedType.LPArray)] int[] arr2);
Sign up to request clarification or add additional context in comments.

Comments

2

I'm not sure but try using fixed:

fixed (int* arr1 = new int[10], arr2 = new int[10])
{
            //acting with arr1 arr2 as you wish
}

Or you can use marshaling

[DllImport("your_dll")]
public extern void IterateCL([In, MarshalAs(UnmanagedType.LPArray)] int[] arr1, [Out, MarshalAs(UnmanagedType.LPArray)] int[] arr2);

4 Comments

@ILya: Yeap, it isn't necessary.
@abatishchev Why without OutAttribute? I thought we need to return a value from C++ to C# but InAttibute is only one direction.
As far as I understand from OP function declaration the first param is only In and the second - in Out. Though you can specify both attributes for both params but I guess it will be overuse
@abatishchev, Oh sure you are right! I have to read more carefully.

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.