There is this example: http://limbioliong.wordpress.com/2011/03/20/c-interop-how-to-return-a-variant-from-an-unmanaged-function/
In the end they use directly an IntPtr
(they use it as a return value, you would have to use it as a out IntPtr
), then Marshal.GetObjectForNativeVariant()
, VariantClear()
and Marshal.FreeCoTaskMem()
from the C# side, while on the C/C++ side the VARIANT
was allocated with CoTaskMemAlloc()
.
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)]
static extern void MyFunction(out IntPtr ptr);
[DllImport("oleaut32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
static extern Int32 VariantClear(IntPtr pvarg);
IntPtr pVariant;
MyFunction(out pVariant);
object objRet = Marshal.GetObjectForNativeVariant(pVariant);
VariantClear(pVariant);
Marshal.FreeCoTaskMem(pVariant);
pVariant = IntPtr.Zero;
Clearly you could expose another C function in your dll that frees the VARIANT
(it's always correct to expose Free
methods in your library, so that caller can use them and not ask himself "how should I free this memory?")