C# pinvoke C char array -
marshalling char array.
the c typedef of function is:
typedef bool (*get_variableinfofunc)(int *, char * *, int *, int *); it`s usage like:
pnvariableidarray = new (nothrow) int[numvars]; pcvariablename = new (nothrow) char*[numvars]; (int = 0; < numvars; i++) { pcvariablename[i] = new char[100]; } pnunvariableidarray = new (nothrow) int[numvars]; pnvariabletype = new (nothrow) int[numvars]; res = get_variableinfo(pnvariableidarray, pcvariablename, pnunvariableidarray, pnvariabletype); my c# signature is:
[dllimport(autodynresultsapidll, entrypoint = "get_variableinfo", setlasterror = true)] [return: marshalas(unmanagedtype.bool)] public static extern bool getvariableinfo( int[] pnvariableidarray, intptr[] pcvariablename, int[] pnunvariableidarray, int[] pnvariabletype); i use like:
var stringpointers= new intptr[numvars]; (int = 0; < numvars; i++) { by[i] = marshal.allochglobal(100); } getvariableinfo(pnvariableidarray, stringpointers, pnunvariableidarray, pnvariabletype); and string with:
var strings = new string[numvars]; (int = 0; < numvars; i++) { strings[i] = marshal.ptrtostringansi(by[i]); } is there nicer way doing without freeing memory of pointer. copy char array string array?
first of all, few problems code stands:
- the calling convention
cdecl, need includecallingconvention = callingconvention.cdeclin attribute. - you set
setlasterror = true, unmanaged function surely not callsetlasterror. if so, removesetlasterror = true. - you call
allochglobalthere no matching callfreehglobal, , memory leaked. - your assumption no string exceed length of 100 (including null terminator) seems brittle, , @ risk of buffer overflow.
as far main body of question goes, marshaller won't marshal array of strings you. current approach, subject provisos above, correct way tackle problem.
Comments
Post a Comment