Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.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/5/google-sheets/3.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# DLL导入malloc双间接指针_C#_C_Dll_Dllimport - Fatal编程技术网

C# DLL导入malloc双间接指针

C# DLL导入malloc双间接指针,c#,c,dll,dllimport,C#,C,Dll,Dllimport,我有一个C函数,它接受多个双间接指针参数 像这样的 int myFunction (int ** foo, int** bar, int **baz){ int size = figureOutSizeFunction(); *foo = (int*) malloc (sizeof(int) * size); return SomeOtherValue; } 现在在C#中,我试图将其作为一个ref传递给一个IntPtr,但是IntPtr始终为零。当我将这些值传递给下一个

我有一个C函数,它接受多个双间接指针参数

像这样的

int myFunction (int ** foo, int** bar, int **baz){
    int size = figureOutSizeFunction();
    *foo = (int*) malloc (sizeof(int) * size);
    return SomeOtherValue;
}
现在在C#中,我试图将其作为一个ref传递给一个IntPtr,但是IntPtr始终为零。当我将这些值传递给下一个DLL C函数时,DLL将失败,并出现系统访问冲突。我知道该代码只在C环境中工作(我有一个“main”来测试代码),但是,当从C调用它时,它不工作#


我在C#中需要什么变量类型才能传递到C DLL?参考整数

处理双指针(
**
)时,最好的方法是将它们封送为
IntPtr

public static extern int myFunction(IntPtr foo, IntPtr bar, IntPtr baz);
public static class Extensions {
  public static T Deref<T>(this IntPtr ptr) {
    return (T)Marshal.PtrToStructure(ptr, typeof(T));
  }
}
然后在托管代码中挖掘双指针

IntPtr foo, bar baz;
...
myFunction(foo, bar, baz); 

IntPtr oneDeep = (IntPtr)Marshal.PtrToStructure(foo, typeof(IntPtr));
int value = (int)Marshal.PtrToStructure(oneDeep, typeof(int));
上面的代码显然有点。。。丑陋的。我更喜欢在
IntPtr
上用漂亮的扩展方法包装它

public static extern int myFunction(IntPtr foo, IntPtr bar, IntPtr baz);
public static class Extensions {
  public static T Deref<T>(this IntPtr ptr) {
    return (T)Marshal.PtrToStructure(ptr, typeof(T));
  }
}
公共静态类扩展{
公共静态文件(本文件){
返回(T)Marshal.ptr结构(ptr,typeof(T));
}
}
然后,可以将上述内容重写为更具可读性的内容

int value = ptr.Deref<IntPtr>().Deref<int>();
int value=ptr.Deref().Deref();

您希望传递
ref IntPtr
,然后使用
Marshal.PtrToStructure
读取数组。然后,您需要再次调用DLL以调用free。最后,为什么要转换malloc()的返回值?那太糟糕了。