c++ cli - C++/CLI pointer issue = fun! -


i've been converting bunch of old c++ code c++/cli code, , think i've coded myself corner.

my goal take unmanaged c++ library , bunch of header files , expose functionality c# solution. reading on internet, standard way to:

  • create 2 c++ classes: 1 managed, other unmanaged.
  • the unmanaged class wrangle objects in c++ library provide desired functionality.
  • the managed class wrap of public methods in unmanaged class. each wrapper method handle necessary conversions string^ string, etc..

but, scenario isn't complex, decided try , implement in 1 class. wrestling peculiar problem generates accessviolationexceptions.

my header file looks this:

public ref class managedclass { public:   managedclass();   void createunmanagedobject(string^ param1);   void useunmanagedobject();    unmanagedobject *myunmanagedobject; } 

and cpp file looks this:

void managedclass::createunmanagedobject(string^ param1) {    /* convert params, use them in way. */     /* capture output of library call pointer defined in managedclass.*/    myunmanagedobject= &(librayobject.librarymethod1());   } void managedclass::useunmanagedobject() {    /* function pass unmanaged object     * library function work on it.     */    libraryobject.librarymethod2(*myunmanagedobject);    /* whoops! system.accessviolationexception thrown! */ } 

the intriguing thing if call librarymethod2 within createunmanagedobject after librarymethod1, works fine. after createunmanagedobject exits, seems memory pointed myunmanagedobject lost.

can see reason happening?

edit: library declarations this:

unmanagedobject librarymethod1(); void librarymethod2(unmanagedobject &param); 

are not taking address of temporary variable? if

libraryobject.librarymethod1() 

returns copy of value, taking address of local variable, goes out of scope @ end of method. using address afterwards undefined behavior, in case causing access violations!


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -