I've been converting a bunch of old C++ code into C++/CLI code, and I think I've coded myself into a corner.
My goal was to take an unmanaged c++ library and a bunch of header files and expose their functionality to a C# solution. From reading on the internet, the standard way to do this is to:
- Create two c++ classes: one managed, the other unmanaged.
- The unmanaged class will wrangle the objects in the c++ library to provide the desired functionality.
- The managed class will wrap all of the public methods in the unmanaged class. Each wrapper method would handle the necessary conversions from String^ to string, etc..
But, my scenario isn't very complex, so I decided to just try and implement everything in one class. I am now wrestling with a peculiar problem that generates AccessViolationExceptions.
My header file looks like this:
public ref class ManagedClass
{
public:
ManagedClass();
void CreateUnmanagedObject(String^ param1);
void UseUnmanagedObject();
UnmanagedObject *myUnmanagedObject;
}
And my cpp file looks like this:
void ManagedClass::CreateUnmanagedObject(String^ param1)
{
/* Convert params, use them in some way. */
/* capture the output of this library call to the pointer defined in ManagedClass.*/
myUnmanagedObject= &(LibrayObject.LibraryMethod1());
}
void ManagedClass::UseUnManagedObject()
{
/* This function will pass the Unmanaged object into
* a library function which will do some work on it.
*/
LibraryObject.LibraryMethod2(*myUnmanagedObject);
/* Whoops! System.AccessViolationException is thrown! */
}
The intriguing thing is that if I call LibraryMethod2 within CreateUnmanagedObject immediately after LibraryMethod1, it works fine. But after CreateUnmanagedObject exits, it seems that the memory pointed to by myUnmanagedObject is lost.
Can anyone see a reason that this is happening?
Edit: Library declarations look like this:
UnmanagedObject LibraryMethod1();
void LibraryMethod2(UnmanagedObject ¶m);