I have a DLL that is developed in C ++, included in a C # project, and I have strange AccessViolationExceptions happening irrationally. I suspect that my garbage is not collected correctly. I have an unmanaged apiGetSettings method (from the DLL) that should copy data to the Settings object (this is actually a structure in the source code, but .NET InterOp allowed me to import data as objects of the class. I use System.Runtime.InteropServices. Marshal methods allocating and freeing memory, but it can leave garbage that crashing everything.
Now, should I implement the IDisposable methods in the Settings class (unmanaged?). If so, how can I get rid of strings ordered as UnmanagedType.ByValTStr, and how can I get rid of settings objects?
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
class Settings
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 33)]
internal string d;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
internal string t;
internal int b;
}
[DllImport(".\\foobar.dll", EntryPoint = "getSettings")]
private static extern int apiGetSettings(IntPtr pointerToSettings);
void GetSettings(ref Settings settings)
{
int debug = 0;
IntPtr pointerToSettings = Marshal.AllocHGlobal(43);
Marshal.StructureToPtr(settings, pointerToSettings, true);
debug = apiGetSettings(pointerToSettings);
Marshal.PtrToStructure(pointerToSettings, settings);
Marshal.FreeHGlobal(pointerToSettings);
}
entro source
share