Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.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# P/在结构中调用定义长度的C char*数组_C#_C++_.net_C - Fatal编程技术网

C# P/在结构中调用定义长度的C char*数组

C# P/在结构中调用定义长度的C char*数组,c#,c++,.net,c,C#,C++,.net,C,我已经查找了一段时间,但没有找到一篇文章提供了这个问题的答案,所以希望它不是重复的 我一直在用一个struct进行p/Invoking,这很好,但后来我看到: char*infoString[SIDTUNE\u MAX\u CREDIT\u STRINGS] 其中,SIDTUNE_MAX_CREDIT_字符串定义为10 因此,将所有内容内联,结构成员定义为: char*infoString[10] 现在,这与我试图解决的其他问题略有不同 char*数组包含指向其他C字符串的指针 在这种特定情况下

我已经查找了一段时间,但没有找到一篇文章提供了这个问题的答案,所以希望它不是重复的

我一直在用一个struct进行p/Invoking,这很好,但后来我看到:

char*infoString[SIDTUNE\u MAX\u CREDIT\u STRINGS]

其中,SIDTUNE_MAX_CREDIT_字符串定义为10

因此,将所有内容内联,结构成员定义为:

char*infoString[10]

现在,这与我试图解决的其他问题略有不同

char*数组包含指向其他C字符串的指针

在这种特定情况下,只使用了3个索引,而保留了其余索引。指标如下:

  • infoString[0]=歌曲标题

  • infoString[1]=艺术家姓名

  • infoString[2]=版权所有/发布者


我如何从C#访问这些字符串中的每一个来p/调用它?使每个单独返回的C++函数不是一个选项。

< P>假设函数类似于<代码> GETPONINFING(int宋德,LPInfostring songinfo)< /C>,可以定义<代码> Stutt,它有一个数组:<代码> INTPTR < /C>。但是,您必须注意内存泄漏,因为调用函数可能希望您释放为返回的字符串分配的内存

目标.h:

typedef struct SongInfo
{
    char* infoString[10];
} *LPSongInfo;

extern "C" __declspec(dllexport) int GetSongInfo(int songID, LPSongInfo info);
具体目标c:

extern "C" __declspec(dllexport) int GetSongInfo(int songID, LPSongInfo demo)
{
    demo->infoString[0] = "Hello world";
    demo->infoString[1] = "Hello 1";
    demo->infoString[2] = "Hello 2";

    return TRUE;
}
p/调用签名:

[DllImport("PInvokeDll.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int GetSongInfo(int songID, out SongInfo ts);

[StructLayout(LayoutKind.Sequential)]
struct SongInfo
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public IntPtr[] infoString;
};
示例用法:

SongInfo siStruct;
var num2 = GetSongInfo(101, out siStruct);

// copy the results to managed memory
var results = new string[10];
for (int i = 0; i < 10; i++)
{
    if (siStruct.infoString[i] != IntPtr.Zero)
    {
        // if these were Unicode strings, this would change to PtrToSTringUni
        results[i] = Marshal.PtrToStringAnsi(siStruct.infoString[i]);
    }
}

// results now holds the .Net strings
// if there is an expectation of the caller to free the struct 
// strings, that should happen now

请看,这个问题只提供了关于如何处理C中的实际字符串(即字符数组)的答案,而不是关于如何P/调用指向C字符串的指针数组的答案。。。我没注意到。请参阅下面的答案。谢谢,这帮了大忙。
[StructLayout(LayoutKind.Sequential)]
struct SongInfo2
{
    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStr, SizeConst = 10)]
    public string[] infoString;
};