3

我在C中有这个结构

struct system_info
{  
   const char *name;     
   const char *version;  
   const char *extensions; 
   bool        path;    
};

而这个函数签名

void info(struct system_info *info);

我正在尝试像这样使用此功能:

[DllImport("...")]
unsafe public static extern void info(info *test);



[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct info
{
    public char *name;
    public char *version;
    public char *extensions;

    public bool path;
} 

而在我的主要:

info x = new info();
info(&x);

我收到一个错误,指针无法引用封送结构,我该如何管理?

4

2 回答 2

3

完全没有必要在unsafe这里使用。我会这样做:

public struct info
{
    public IntPtr name;
    public IntPtr version;
    public IntPtr extensions;
    public bool path;
}

然后函数是:

[DllImport("...")]
public static extern void getinfo(out info value);

您可能需要指定Cdecl调用约定,具体取决于本机代码。

像这样调用函数:

info value;
getinfo(out value);
string name = Marshal.PtrToStringAnsi(value.name);
// similarly for the other two strings fields

由于在您发布的本机代码中没有提及字符串长度,我假设这些字符串是由本机代码分配的,并且您不需要做任何事情来解除分配它们。

于 2013-02-09T08:40:51.897 回答
0

通过使用 ref 而不是 *test 像 Hans Passant 提到的那样解决

[DllImport("...")]
unsafe public static extern void info(ref system_info test);
于 2013-02-09T03:02:38.957 回答