Wednesday, 15 January 2014

c# - Function takes pointer to structure -



c# - Function takes pointer to structure -

i have construction in c

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

and function signature

void info(struct system_info *info);

i'm trying utilize function 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 on main:

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

i'm getting error, pointers cannot reference marshaled structures, how can manage this?

there's no need @ utilize unsafe here. this:

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

and function is:

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

you may need specify cdecl calling convention, depending on native code.

call function this:

info value; getinfo(out value); string name = marshal.ptrtostringansi(value.name); // other 2 strings fields

since there no mention of string length in native code posted, i'm assuming strings allocated native code , don't need to deallocate them.

c# pinvoke

No comments:

Post a Comment