c++ - Attempted to read or write protected memory with dllimport in c# -


i have problem project: in dll c++:

    extern "c" __declspec(dllexport) int results(char* imginput, void* tree) {        struct kd_node* nodetree = new(tree)kd_node ; // new kd_tree data memory address     ...      ...     int ret = atoi(retvaluestr.c_str());     return ret; }  extern "c" __declspec(dllexport) void* buildkdtree(char* folder) {     struct kd_node* kd_root;     ....      feature *lfdata = listfeat.data();     kd_root = kdtree_build(lfdata,listfeat.size());     void* address_kdtree = (void*)&kd_root; // memory address of kd_tree     return address_kdtree; } 

and use dllimport in c#:

[dllimport(@"kdtreewithsift.dll", entrypoint = "buildkdtree", charset = charset.ansi, callingconvention = callingconvention.cdecl)] public unsafe static extern void* buildkdtree(byte[] urlimage);   [dllimport(@"kdtreewithsift.dll", entrypoint = "results", charset = charset.ansi, callingconvention = callingconvention.cdecl)] [return:marshalas(unmanagedtype.i4)] public unsafe static extern int results(byte[] imginput, void* tree);  static unsafe void main() {      string urlimg1 = "c:/users../test img/1202001t1.jpg";      string urlimg = "c:/export_features";        try      {        intptr result;      int result1;      result1 = results(convertstringtobyte(urlimg1), 5, buildkdtree(convertstringtobyte(urlimg))); //  error      console.writeline("results = %d",result1);      }      catch (exception ex)      {           console.writeline(ex);           console.readline();      } } 

when run program, program show error : attempted read or write protected memory. indication other memory corrupt

what error know , how resolved ? thank you!

you don't need convertstringtobyte method here. can tell runtime marshal string char *. also, suggest make method return intptr, this:

[dllimport(@"kdtreewithsift.dll", entrypoint = "buildkdtree",     charset = charset.ansi, callingconvention = callingconvention.cdecl)] public static extern intptr buildkdtree([marshalas(unmanagedtype.lpstr)]string urlimage);  [dllimport(@"kdtreewithsift.dll", entrypoint = "results",     charset = charset.ansi, callingconvention = callingconvention.cdecl)] [return:marshalas(unmanagedtype.i4)] public static extern int results([marshalas(unmanagedtype.lpstr)]string imginput, intptr tree); 

you can call with:

intptr tree = buildkdtree(urlimg); int result1 = results(urlimg, 50, tree);  console.writeline("results = {0}",result1); 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -