I am getting two errors when i try to call dscDIOSetConfig external
function:
Error 1 The best overloaded method match for
'dllimport.Program.dscDIOSetConfig(short, System.IntPtr)' has some
invalid arguments C:\YB\dllimport\dllimport\Program.cs 25 21 dllimport
Error 2 Argument '2': cannot convert from 'int[]' to 'System.IntPtr' C:
\YB\dllimport\dllimport\Program.cs 25 44 dllimport
[...]
public static extern byte dscDIOSetConfig(short board, IntPtr
config_bytes);
[...]
short board; //Handle of the Digital I/O board to operate
int[] config_bytes = new int[2];
[...]
result = dscDIOSetConfig(board, config_bytes);
Well, the reason for the error is clear: You are passing an arrayof
ints where an IntPtr is expected instead.
The remedy is not simple. It is not enough to take the address ofthe
array and pass it as a pointer, because the array is a managed object andit
could be moved around, which would cause a lot of trouble when the unmanaged
code attempted to access data at the original address which you passed in
the pointer. You have to allocate a fixed block of memory and "pin" it, so
that it won't move around. One way to do it is the following:
GCHandle pinnedRawData = GCHandle.Alloc(config_bytes, GCHandleType.Pinned);
IntPtr pinnedRawDataPtr = pinnedRawData.AddrOfPinnedObject();
result = dscDIOSetConfig(board, pinnedRawDataPtr);
pinnedRawData.Free();