How do I invoke this native method from C#
I want to invoke one/many functions of a native library but I am unsure on the type mappings. The function in particular I am currently trying is as follows, here is the small console app which I am spiking in:
extern char *tgetstr (const char *name, char **area);
And here is my attempt at mapping this to use in a .NET console. I get an error saying, trying to read or write protected memory.
class Program
{
[DllImport("termcap.dll")]
public static extern IntPtr tgetstr(IntPtr name, IntPtr area);
static void Main(string[] args)
{
IntPtr ptr1 = new IntPtr();
IntPtr a = tgetstr(Marshal.StringToCoTaskMemAnsi("cl"), ptr1);
Console.WriteLine(Marshal.PtrToStringBSTR(a));
}
}
TIA
A开发者_开发知识库ndrew
You need to pass your IntPtr
by ref
, so the function can overwrite it. Then you also need to free the string after you've copied it, hopefully the DLL provides a matching deallocation function. StringToCoTaskMemAnsi
isn't helping you any either, it's just leaking memory.
The correct p/invoke declaration is probably
[DllImport("termcap.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr tgetstr(string name, ref IntPtr area);
I haven't worked with unmanaged code since 3 years but I think you can do it by marking the method parameters with MarshalAs attribute. Check this article,
MSDN
You have to pin your ptr1.
GCHandle handle = GCHandle.Alloc(ptr1, GCHandleType.Pinned);
精彩评论