How to get a pointer to non starting item of an array

M

marco_segurini

Hi,

I have a c++ dll that exports a function with this signature:
extern "C" void WINAPI Dump(int * pvInt, int iLen);

Calling this function from C# code is not a problem if I want to pass
the whole array:
....
[DllImport("PartialArrayPassingDll.dll")]
public extern static void Dump(int[] vInt, int iLen);
....
int[] vInt = new int[5];
Dump(vInt, vInt.Length);
....

Now I like to now if there is a way to do a call like:
'Dump(vInt+2, vInt.Length-2)' //this is pseudo code
instead to declare a wrapper function and use a GCHandle
like shown in my example.

thanks.
Marco.

//Code sample start here

using System;
using System.Runtime.InteropServices;

namespace PartialArrayPassing
{
class Class1
{
[DllImport("PartialArrayPassingDll.dll")]
public extern static void Dump(int[] vInt, int iLen);
//extra function I like to avoid
[DllImport("PartialArrayPassingDll.dll")]
public extern static void DumpIP(IntPtr vInt, int iLen);

[STAThread]
static void Main()
{
int[] vInt = new int[5];
for (int iPos=0; iPos<vInt.Length; ++iPos)
vInt[iPos] = iPos;

//Whole array passed
Dump(vInt, vInt.Length);

//Partial array passed
const int iStartPos = 2;
GCHandle gch = GCHandle.Alloc(vInt, GCHandleType.Pinned);
DumpIP((IntPtr)((int)gch.AddrOfPinnedObject()+Marshal.SizeOf(typeof(int))*iStartPos),
vInt.Length-iStartPos);
gch.Free();
}
}
}

//Code sample end here
 
N

Nicholas Paldino [.NET/C# MVP]

Marco,

You have a few options here. The first would be to copy the elements
into a new array, copying only the elements that you want to pass through.

The second is to work with unsafe code, which will allow you to perform
pointer arithmetic and then you can just pass the pointer to the new section
of code.

However, you have to determine which approach is best for you. Unsafe
code might not be an option. Also, if you are performing this interop call
only a few times, you probably don't want to go that route (unless the
number of elements in the array is typically going to be excessive and a
copy would really hamper performance).

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top