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);
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();
}
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(); }
}
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.