All,
My question is:
Is it possible to return a pointer allocated in managed code to unmanged code.
I have an unmanged C++ application that calls into a C# dll. The C# dll is build as a CCW and the unmanaged app is build with /clr. I would like to have the unmanaged app be able to get an unmanaged pointer from the C# dll and then read its content. The problem I am running into is that the pointer gets moved so that the unmanged code asserts.
I've seen articles referring to GCHandle but I can't figure out how to call it. Does the managed code call get the handle or the unmanaged code?
A sample of the code is below.
Any help on this would be greatly appreciated.
TIA,
Dale
Code:
// Unmanaged application
int _tmain(int argc, _TCHAR* argv[])
{
// Get a pointer to the CCW Object
GBVssNetInterface::_GBVssDeviceComm *pNetInterface;
CoInitialize(NULL);
GBVssNetInterface::_GBVssDeviceCommPtr p(__uuidof (GBVssNetInterface::GBVssDeviceComm));
pNetInterface = p;
__int64 pLuns;
pNetInterface->GetAllVisableLuns(&size, (LONG*)&pLuns);
// Blows up
GlobalFree((HGLOBAL)pLuns);
return 0;
}
// Managed object
namespace GBVssNetInterface
{
[Guid("D6F88E95-8A27-4ae6-B6DE-0542A0FC7039")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface _GBVssDeviceComm
{
[DispId(1)]
//unsafe int GetAllVisableLuns(int* size, char* pLunBuffer);
unsafe int GetAllVisableLuns(ref int size, ref Int64 pLunBuffer);
}
[Guid("4CB08BDA-7F12-458a-AE0B-B6C4E4441822")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("GBVssNetInterface.GBVssDeviceComm")]
public class GBVssDeviceComm : _GBVssDeviceComm
{
public GBVssDeviceComm() {}
public unsafe int GetAllVisableLuns(ref int Size, ref Int64 pLunBuffer)
{
IntPtr lunBuffer = Marshal.AllocHGlobal(size);
pLunBuffer = lunBuffer.ToInt64();
return 0;
}
}
}