Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从C调用这个本机方法#_C#_C++_Interop - Fatal编程技术网

C# 如何从C调用这个本机方法#

C# 如何从C调用这个本机方法#,c#,c++,interop,C#,C++,Interop,我想调用本机库的一个/多个函数,但不确定类型映射。我目前正在尝试的功能如下,下面是我正在使用的小型控制台应用程序: extern char *tgetstr (const char *name, char **area); 下面是我尝试将其映射到.NET控制台中使用的方法我收到一条错误消息,表示试图读取或写入受保护的内存。 class Program { [DllImport("termcap.dll")] public static extern IntPtr tgetstr

我想调用本机库的一个/多个函数,但不确定类型映射。我目前正在尝试的功能如下,下面是我正在使用的小型控制台应用程序:

extern char *tgetstr (const char *name, char **area);
下面是我尝试将其映射到.NET控制台中使用的方法我收到一条错误消息,表示试图读取或写入受保护的内存。

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));
    }
}
短暂性脑缺血发作


Andrew

我已经三年没有使用过非托管代码了,但我认为可以通过使用MarshalAs属性标记方法参数来实现。看看这篇文章


您必须固定ptr1


GCHandle handle=GCHandle.Alloc(ptr1,GCHandleType.pinted)

您需要通过
ref
传递
IntPtr
,以便函数可以覆盖它。然后,您还需要在复制字符串后释放该字符串,希望DLL提供匹配的释放函数
StringToCoTaskMemAnsi
也帮不了你什么忙,只是内存泄漏

正确的p/invoke声明可能是

[DllImport("termcap.dll", CharSet = CharSet.Ansi)]
public static extern IntPtr tgetstr(string name, ref IntPtr area);

这只会影响
ptr1的地址,而不会影响值(存储在其中的地址),因此不会有任何区别。另外,p/invoke层将自动执行此操作。