I am writing a Visual Studio add in and need to marshall a managed CodeElements object to it's unmananged form. I just need the pointer in memory, as I can cast it and treat it like a CodeElement on the unmanaged side.
[DllImport("CodeMethodsToString.dll")]
private static extern BSTR* CodeMethodsToString(void* functionObject);
public static void CodeMethodsToXML(XmlElement parent, CodeElements elements)
{
//Call CodeMethodsToString: how do I marshall CodeElements to an IntPtr?
//set XmlElement in here
}
I know how to deal with the XML, and I have a working version of this in C#. I created the unmanaged DLL because calling all of the various member variables at the lowest level of recursion was killing the speed of the program. I simply need to know how to use System.Runtime.Interop.Marshal to convert the CodeElements object to a pointer to the COM object in memory.
Thanks.
Looks like Jonathan was close. This is how I'd do it:
[DllImport("CodeMethodsToString.dll")]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string CodeMethodsToString(IntPtr functionObject);
public static void CodeMethodsToXML(XmlElement parent, CodeElements elements)
{
GCHandle pin;
try
{
pin = GcHandle.Alloc(elements, GCHandleType.Pinned);
string methods = CodeMethodsToString(pin.AddrOfPinnedObject());
}
finally
{
pin.Free();
}
}