我有一个C++类,我想在C#中使用。为此,我正在尝试使用可调用函数(使用“extern C和__declspec(dllexport)”)编写其他C++ dll来包装此类(它是其他库的一部分)。 我的想法是保留一个指向我的对象的指针,并将它发送给包装器DLL中的函数,然后从那里调用该对象的方法。这看起来很好,但当对象具有解构器时会发生问题。当使用C#使用C++对象时析构函数执行PInvoke
这是我的C++包装代码:(设备是我的C++类/对象)
__declspec(dllexport) Status Device_open(Device* di, const char* uri)
{
Device dl;
Status status = dl.open(uri);
di = &dl;
return status;
}
__declspec(dllexport) void Device_Close(Device* di)
{
di->close();
}
这是我的C#包装代码:
[DllImport("Wrapper.dll")]
static extern Status Device_open(ref IntPtr objectHandler, IntPtr uri);
public static Device Open(string uri)
{
IntPtr handle = IntPtr.Zero;
Device_open(ref handle, Marshal.StringToHGlobalAnsi(uri));
return new Device(handle);
}
[DllImport("Wrapper.dll")]
static extern void Device_Close(IntPtr objectHandler);
public void Close()
{
Device_Close(this.Handle);
}
这里是C#的应用程序测试的代码:
Device d = Device.Open(di.URI);
d.Close();
每件事情都很好。问题在于,当我请求打开一个新设备时,主C++对象的Deconstructor将被执行,所以我的关闭请求总是返回异常(因为它已经关闭或被销毁);
我该怎么做才能防止这种情况?
仅供参考,没有* deconstructors * C++中。它们被称为*析构函数*。 :) – jalf 2013-02-11 17:13:46
@jalf,谢谢你的提示。 +1 – 2013-02-11 18:39:15