The function takes a pointer to a structure

I have this structure in C

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

      

And this function signature

void info(struct system_info *info);

      

I am trying to use this function like this:

[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;
} 

      

And in my main:

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

      

I am getting the error, pointers cannot reference marshaled structures, how can I manage this?

+3


source to share


2 answers


No need to use unsafe

here. I would do it like this:

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

      

And then the function:

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

      



You may need to specify a calling convention Cdecl

, depending on your own code.

Call the function like this:

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

      

Since there is no mention of line length in the source code you posted, I am assuming that the lines are allocated with your own code and that you don't need to do anything to free them.

+3


source


Decided to use ref instead of * test as Hans Passant mentioned



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

      

0


source







All Articles