Declare a user32.dll function to accept an Array

  • Thread starter Thread starter Richard A. Lowe
  • Start date Start date
R

Richard A. Lowe

I'm successfully using SendInput to emulate mouse events
for a legacy app, delcared like so:

[DllImport("User32.dll")]
public extern static int SendInput( int theCount, ref
INPUT pInputs, int theSize );

From the MSDN docs, SendInput appears to take an array of
inputs:

"pInputs
[in] Pointer to an array of INPUT structures. Each
structure represents an event to be inserted into the
keyboard or mouse input stream."

However I'm not sure how to pass it in managed C#. I
recklessly made an attempt by simply changing the
declaration to an array (as below). And as I suspected it
does *not* work when I pass in a valid array of INPUT
structs.

[DllImport("User32.dll")]
public extern static int SendInput( int theCount, ref INPUT
[] pInputs, int theSize );

I'm wondering:
a) How to declare the external function correctly
b) How to create and pass my INPUT structs array.
c) I'd like to know the why of the internals? I.E. Does it
not work because .NET is also marshalling the 4 bytes of
length info at the begining of the array?

Thanks
 
Richard,
a) How to declare the external function correctly

Just remove the ref keyword.

[DllImport("User32.dll")]
public extern static int SendInput( int theCount, INPUT[] pInputs, int
theSize );

b) How to create and pass my INPUT structs array.

Just like you would when calling a managed method.

c) I'd like to know the why of the internals? I.E. Does it
not work because .NET is also marshalling the 4 bytes of
length info at the begining of the array?

An array is a reference type, and when you pass an array by value to
unmanaged code it will get a pointer to the first item. Adding the ref
modifier adds another level of indirection, so the unmanaged code gets
a pointer to a pointer to an INPUT struct.

You may want to look at this MSDN TV episode for more information

http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20030424NETFXSK/manifest.xml



Mattias
 
Back
Top