Pergunta

My unmanaged C++ DLL has a function with a POINT out parameter:

void GetPosition(int iItemIndex, POINT *pt)

I am trying to PInvoke the function in my C# application:

[DllImport(@"unmanaged.dll")]
public static extern void GetPosition(int iItemIndex, System.Drawing.Point pt);

My question is, should I use System.Drawing.Point as the C# equivalent of POINT? Modifying the unmanaged code is an option. Should I use two longs instead?

void GetPosition(int iItemIndex, long *x, long *y)
Foi útil?

Solução

POINT is a C structure, its pinvoke equivalent is a C# struct with two members of type int. System.Drawing.Point already is a perfectly good candidate, no need to write your own.

Beware however that your C# declaration is incorrect. The C declaration uses a POINT*, a pointer to a POINT structure. C declarations are often ambiguous. It can mean that the POINT is passed by reference so that the function fills in the members. Or can mean that the caller is supposed to pass an array of POINT structures. So either of these two C# declarations would be a match:

  public static extern void GetPosition(int iItemIndex, out Point pt);
  public static extern void GetPosition(int iItemIndex, Point[] points);

The array version is highly unlikely, you'd expect the C programmer to use the plural GetPositions(). And there's a problem in that it won't know how large the array is, C arrays are very primitive and have no baked-in Length property.

So surely the proper declaration is:

  [DllImport(@"unmanaged.dll", CallingConvention=CallingConvention.Cdecl)]
  public static extern void GetPosition(int iItemIndex, out Point pt);

Do note that I added the CallingConvention property, it is the default for C code. Remove it if you know for sure that it uses __stdcall.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top