Hi there,
I have some doubts about the using of PInvoke to import dll functions.
Let's see
I have a function which returns a pinter to a structure to open a network
adapter
LPADAPTER PacketOpenAdapter(LPTSRT AdapterName);
and i have other which is used to close the adapter and free the adapter
structure
VOID PacketCloseAdapter(LPADAPTER lpAdapter);
the first thing i have done is to define an adapter structure
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
class LPADAPTER
{
public IntPtr hFile;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst=64)]
public string SymbolicLink;
public int NumWrites;
public IntPtr ReadEvent;
public int ReadTimeout;
}
and do this
[DllImport("packet.dll", CharSet = CharSet.Auto)]
static extern LPADAPTER PacketOpenAdapter(string AdapterName);
[DllImport("packet.dll")]
static extern void PacketCloseAdapter(LPADAPTER lpAdapter);
OK but then i have thinked that if the structure has to be freed by
packetclose adapter then i cannot pass a managed structure and i have to use
IntPtr as well in the DllImports:
[DllImport("packet.dll", CharSet = CharSet.Auto)]
static extern IntPtr PacketOpenAdapter(string AdapterName);
[DllImport("packet.dll")]
static extern void PacketCloseAdapter(IntPtr lpAdapter);
But im not very sure if it is necessary.What is the criteria i have to
follow to decide if i have to use IntPtr's or managed structures???
Thanks
Dmytro Lapshyn [MVP] - 11 Apr 2006 11:15 GMT
Hi,
You can use IntPtr-s because you don't own the memory allocated for the
ADAPTER structure, but you can also keep the structure declaration and use
Marshal.PtrToStruct to copy the data from the IntPtr to the structure.