Hi,
I've got an c++ class we need to use via interop. I wrote a little wrapper
around the methods required using the thiscall calling convention to pass the
pointer when invoking the class's members. (I'm getting an IntPtr to the
class back from another interop call)
The problem is the only exports I've got for the unmanaged type is for the
abstract base class, I'm guessing the ptr I'm getting back is for a concrete
type so some of the ordinal numbers I have is not valid. Ie. All the method
invocations works 100% but for the destructor which is defined as a virtual
method.
My problem is after I'm done with the class there's no way for me to get
this type to dispose properly and this poses a big problem for me at the
moment, hence this post. I'm not sure if it's possible to invoke the concrete
type's destructor from managed code as the ordinal number points to the base
class's method. Apologies if the description don't make all that much sense,
my knowledge of unmanaged code is a bit limited at the moment.
Any pointers (no pun intended) or advice/workarounds would be much
appreciated!
- Armand
I've included some mock code to illustrate the types below :
C++
------------------------------------------
class SomeNativeType
{
public:
virtual ~SomeNativeType();
int Count() const;
};
C#
------------------------------------------
public class SomeWrapper: IDisposable
{
#region Fields
private IntPtr _this;
#endregion
#region Constructor
public SomeWrapper(IntPtr nativeContext)
{
this._this = nativeContext;
}
public int Count
{
get
{
return count(_this);
}
}
private bool _disposed = false;
public void Dispose(bool disposing)
{
if(! _disposed)
{
Close(_this);
_this = IntPtr.Zero;
_disposed = true;
if(disposing)
{
// Free managed resources here
GC.SuppressFinalize(this);
}
}
}
public void Dispose()
{
Dispose(true);
}
~SomeWrapper()
{
Dispose(false);
}
// int Count() const;
[DllImport("native.dll", EntryPoint = "#xx", CallingConvention =
CallingConvention.ThisCall)]
private static extern int count(IntPtr _this);
// virtual ~SomeNativeType();
[DllImport("native.dll", EntryPoint = "#xx", CallingConvention =
CallingConvention.ThisCall)]
private static extern void Close(IntPtr _this);
}
}
Willy Denoyette [MVP] - 12 Nov 2005 23:17 GMT
> Hi,
>
[quoted text clipped - 3 lines]
> pointer when invoking the class's members. (I'm getting an IntPtr to the
> class back from another interop call)
Just currious how you get the this pointer?
> The problem is the only exports I've got for the unmanaged type is for the
> abstract base class, I'm guessing the ptr I'm getting back is for a
[quoted text clipped - 16 lines]
> Any pointers (no pun intended) or advice/workarounds would be much
> appreciated!
Don't try to interop with unmanaged C++ Classes, just write a simple wrapper
using Managed Extentions C++ or (better) C++/CLI (VS2005).
> - Armand
>
[quoted text clipped - 72 lines]
> }
> }