c# - How to properly release memory when doing custom marshaling (ICustomMarshaler) from native to managed? -


my main app in c# , i'm trying write dll (for input-output) should portable (in c or c++ both windows , linux) , accessible both others c++ apps , main c# app.

although inside dll use c++ make life easier, use c-style methods interface, i.e. have extern "c" { /* methods */} in headers. thought better having c++/cli wrapper (hope right choice since i'm far enough, glad hear suggestions on matter).

now in native dll have structs, contain several other structs , arrays. simplify (a lot) following example:

typedef struct astructnative{     size_t     length,     void*      bstructs; }astructnative;  typedef struct bstructnative{     int16_t    a;     int16_t    b; }bstructnative; 

and c# counterparts:

public class astruct { bstruct[]  array; } public struct bstruct { short a; short b; } 

i make use of icustommarshaler , astruct (1) can passed native dll (when writing) or (2) can got dll (when reading back). think i've been successful case (1) (at least works). now, not clear me right procedure case (2). on native dll have similar to:

void readastruct(astructnative &value) {     size_t length = getarraylength();     bstructnative * bstructs = (bstructnative *)malloc(length * sizeof(bstructnative));     /*fill bstructs*/     value.length = length;     value.bstructs = bstructs; } 

on c# side in marshalnativetomanaged read data, questions are:

  1. what supposed in cleanupnativedata(intptr pnativedata)? call marshal.freecotaskmem(pnativedata) gives exception (saying "this may due corruption of heap...")
  2. i guess have provide method on native dll release memory. commonly done here? standard considering dll should portable , used other c++ apps? guess should not have method freeastruct(astructnative &value) otherwise produce further marshaling of struct, hence should freeastruct() , keeping pointer allocated memory in dll?


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -