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:

  1. the calling convention cdecl, need include callingconvention = callingconvention.cdecl in attribute.
  2. you set setlasterror = true, unmanaged function surely not call setlasterror. if so, remove setlasterror = true.
  3. you call allochglobal there no matching call freehglobal, , memory leaked.
  4. 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

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -