المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Marshalling array segment from C# to C++



C# Programming
11-13-2009, 03:16 AM
Hello,

Time to defer to the experts. I have a C# app and a native C++ function in a separate dll. I need to pass a portion of an array by reference to the native code. I've worked with P/Invoke a little bit, but it's still a bit new to me. I've found plenty to P/Invoke examples for passing a whole array, but I haven't found anything specifically for passing a portion of an array. The native function's signature is void foo(int* arr, int length)and is meant to be called in native C++ like so:for(int i = 0; i < length; i += stepSize)
{
foo(&arr[i], stepSize);
}I cannot modify the code for foo. From MSDN (http://msdn.microsoft.com/en-us/library/hk9wyw21(VS.80).aspx)[^ (http://msdn.microsoft.com/en-us/library/hk9wyw21(VS.80).aspx)], it looks like to pass the entire array I would use[DllImport( "nativeLib.dll")]
public static extern void foo([In, Out] int[] arr, int length); and I can call it as foo(arr, arr.Length);

Now to my question (more like a sanity check). If I want to call foo as in the loop above, should my declaration be [DllImport("nativeLib.dll")]
public static extern void foo(IntPtr arr, int length); and my call be unsafe
{
IntPtr unmanagedArr = Marshal.AllocHGlobal(arr.Length * sizeof(int));
Marshal.Copy(arr, 0, unmanagedArr, arr.Length);
for(int i = 0; i < length; i += stepSize)
{
// Ignore bounds checking for now, this is just conceptual.
foo(new IntPtr(unmanagedArr.ToInt64() + i), stepSize);
}
Marshal.Copy(unmanagedArr, arr, 0, arr.Length);
Marshal.FreeHGlobal(unmanagedArr);
}

Thanks,

Dybs

The shout of progress is not "Eureka!" it's "Strange... that's not what i expected". - peterchen