How to return bytes to C#/.net from C? -
here's c function:
dll_public void alve_ripemd320__finish(void* instance, uint32_t* out_hash) { ... (uint32_t i=0, i_end=10; i<i_end; i++) { out_hash[i] = h[i]; } }
and here how i'm calling c#:
[dllimport(platformconstants.dllname)] static extern void alve_ripemd320__finish (intptr instance_space, ref byte[] hash); ... public byte[] finish() { byte[] result = new byte[40]; alve_ripemd320__finish (c_instance, ref result); return result; }
and produces ugly segfault, goes away if comment c-code above writes out_hash.... question is, correct way of passing buffer of bytes using pinvoke?
your c api writing unsigned integers. typically expect mapped as:
[dllimport(platformconstants.dllname, callingconvention=callingconvention.cdecl)] static extern void alve_ripemd320__finish(intptr instance_space, uint[] hash); public uint[] finish() { uint[] result = new uint[10]; alve_ripemd320__finish (c_instance, ref result); return result; }
there 3 main changes here:
- i switched calling convention
cdecl
. standard c++ compiler (unless you're explicitly switchingstdcall
indll_public
). - i changed match c api, uses 32 bit unsigned integers instead of bytes. should able switch
byte[]
if choose, however. - you shouldn't need pass
ref
. typically equivelent of c api acceptinguint32_t** out_hash
, notuint32_t* out_hash
, should map array directly.
Comments
Post a Comment