问题在PInvoke与char**参数,字符串数组不工作

本文关键字:字符串 数组 工作 参数 PInvoke char 问题 | 更新日期: 2023-09-27 18:08:18

我有一个用C编写的DLL文件。我试图在托管代码中使用它,但我的功能无法正常工作。这是C代码。

int preProcessImagesC (char *p_trainingFilePath,
                       char **p_vecImageFilesOrDirs);  

这个函数工作正常

托管代码:

unsafe private static extern int preProcessImagesC(
    //Works perfact 
    String p_trainingFilePath,
    //char** thise parameter is taking junk values , String Array is not working
    [MarshalAs(UnmanagedType.SafeArray)] ref String[] p_vecImageFilesOrDirs);

只有第一个参数工作正常。我应该为托管代码中的char **p_vecImageFilesOrDirs参数使用什么?请帮我在C#中编写兼容的代码

问题在PInvoke与char**参数,字符串数组不工作

你试过了吗:

private static extern int preProcessImagesC(
    string p_trainingFilePath,
    string[] p_vecImageFilesOrDirs
);

编组程序自动使用:

[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPTStr)]

这就是你所需要的。

您应该小心这一点,因为您的非托管代码无法确定传递的数组的实际大小。您必须将数组的实际大小作为另一个参数传递给非托管函数,或者在两个地方都使用固定的大小。

字符串已经是一个字符数组了。
因此,您应该可以使用

ref String p_vecImageFilesOrDirs

你正在复制一个数组的引用