如何序列化一个IntPtr(在c#中)指向一个来自c ++ dll的对象 [英] How to serialize a IntPtr (in c#) pointing to a object that comes from a c++ dll
问题描述
我在C#Windows Forms应用程序中使用了一个C ++ dll.
I''ve got a c++ dll that i use in my c# windows forms app.
[DllImport("dllname.dll", EntryPoint = "?dllMethod@@YA_NPBDAAPAEAAH@Z", CallingConvention = CallingConvention.Cdecl)]
private static extern bool dllMethod([MarshalAs(UnmanagedType.LPStr)]string fname, out IntPtr descriptor, out int length);
在我的C#应用程序中,我只想使用该Dll返回的IntPtr数据序列化哈希表...所以我正在这样做:
In my c# app, i just want to serialize a hashtable with the IntPtr data that''s returned by that Dll... So i''m doing this:
[Serializable]
public class TopSurfDescriptor
{
public IntPtr descriptor;
public int length;
}
[Serializable]
public class Descriptors
{
private Hashtable descriptors=null;
public void AddDescriptor(string key,TopSurfDescriptor descriptor)
{
descriptors.Add(key, descriptor);
}
public Descriptors()
{
if (File.Exists(@"Descriptors.dat"))
{
FileStream fs = new FileStream(@"Descriptors.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
descriptors = (Hashtable)formatter.Deserialize(fs);
}
catch (SerializationException){ throw; }
finally {fs.Close(); }
}
else
descriptors = new Hashtable();
}
//AND
public void Save()
{
FileStream fs = new FileStream(@"Descriptors.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, descriptors);
}
catch (SerializationException e){ throw; }
finally { fs.Close(); }
}
如果我不关闭应用程序,则序列化和反序列化工作正常,但是如果我关闭它并以调试模式再次运行(从Visual Studio中),则可以看到反序列化的过程运行良好((我看到hastable包含了所有数据,并且指向正确的TopSurfDescriptor类型的IntPtr,但是如果我将此指针从DLL传递到其他方法,则会出现异常,即内存可能已损坏或无法访问...
当我分析序列化的文件(在磁盘上)时,似乎数据不存在(因为文件很小),而只有IntPtr.因此,我认为问题是这样的事实,即从外部dll返回的对象(内存)不是可序列化的.
if i dont close the app the serialization and deserialization works fine, but if i close it and run it again (from visual studio) in debug mode i can see the process of deserialization working good, (i see the hastable with all the data and the IntPtr pointing to the correct TopSurfDescriptor type, but if i pass this pointer to other method from the DLL i got the exception that the memory can be corrupt or dont have access...
when I analyze the serialized file (on disk) i seems that the data is not there (because the file is to small), but only the IntPtr. So, i think the problem is the fact that the object (memory) that is returned from the external dll is not beeing serializable.
推荐答案
您的TopSurfDescriptor
类是序列化IntPtr
就是它所拥有的.
如果您希望以这种方式保存/加载数据,则需要在内存地址处检索数据并进行客户序列化/反序列化.
YourTopSurfDescriptor
class is serializing theIntPtr
as that is what it holds.
You would need to retrieve the data at the memory address and do customer serialization/deserialization if you wish to save/load it this way.
这篇关于如何序列化一个IntPtr(在c#中)指向一个来自c ++ dll的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!