news.mweb.co.za
3/15/2007 3:46:00 PM
Hi,
I assume I am doing something stupid but I can't see what it is.
I want to pass a structure containing a string from C# to C++.
It passes fine but has a memory leak.
I have the C# interop code below.
If I call Test() I can see a substantial leak even though FreeCoTaskMem()
is called.
If I make the string a constant size it goes away but I don't want to do
that since I will be using ::SysAllocString() in the C++ later.
Can anyone see what I am doing wrong?
Thanks, Vin
-------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace WindowsApplication1
{
class MemoryLeakTester
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Detail
{
[MarshalAs(UnmanagedType.LPWStr)]
public string m_source;
}
// store the pointer so I can free it
IntPtr m_detail;
private string m_source;
public MemoryLeakTester()
{
m_source = "testString";
}
public void Test()
{
for (int i = 0; i < 1000000; ++i)
{
IntPtr test = ToUnmanaged();
}
}
public IntPtr ToUnmanaged()
{
if (m_detail != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(m_detail);
m_detail = IntPtr.Zero;
}
Detail raw = new Detail();
raw.m_source = m_source;
int size = Marshal.SizeOf(raw);
m_detail = Marshal.AllocCoTaskMem(size);
Marshal.StructureToPtr(raw, m_detail, false);
return m_detail;
}
}
}