c# - System.AccessViolationException. Attempted to read or write into protected memory -


i know same question has been discussed. i’m using .dll library (originally written on c++, calling convention stdcall). function description need following:

function eksis_com_read(aportname: pansichar; aportspeed: integer; aid: integer; amem: ansichar; aaddr: word; adata: pbyte; acount: word): boolean; bool eksis_com_read(char[] aportname, int aportspeed, int aid, char amem, word aaddr, byte adata, word acount); 

the description of arguments :

aportname – com-port (example «com2»); aportspeed –data rate; aid –device address; amem – memory type (i,r,f); aaddr –register address; adata – pointer memory address reading held; acount – number of bytes read. 

in vs 2013 using c# wrote following:

[dllimport("eksisexchange.dll", entrypoint = "eksis_com_read", callingconvention = callingconvention.stdcall)] public static extern bool read(char[] aportname, int aportspeed, int aid, char amem, ushort aaddr, ref float adata,    ushort acount); 

but during simulation have eror:

system.accessviolationexception. attempted read or write protected memory.

why happening? , why occur sometimes?

[dllimport("eksisexchange.dll", entrypoint = "eksis_com_read", callingconvention = callingconvention.stdcall, charset = charset.ansi)] public static extern bool read(string aportname, int aportspeed, int aid, char amem, ushort aaddr, byte[] adata, ushort acount); 

you must pass ansi, null terminated string function. easiest thing pass string , let marshaler work. same amem

adata buffer data read. must buffer, example byte[]. create before calling method. put size of buffer in acount.

that signature should used like:

byte[] buffer = new byte[1024]; bool res = read("com1", 19200, 1, 'i', 123, buffer, (ushort)buffer.length); 

note signature illogical: there no place method can return how many bytes did read


Comments