1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Interop: Returning a pointer from C#

Discussion in 'C#' started by daleh@hill-eng.com, Sep 2, 2010.

  1. daleh@hill-eng.com

    daleh@hill-eng.com New Member

    Sep 2, 2010
    Likes Received:
    Trophy Points:

    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.


    // Unmanaged application
    int _tmain(int argc, _TCHAR* argv[])
          // Get a pointer to the CCW Object
         GBVssNetInterface::_GBVssDeviceComm *pNetInterface;
         GBVssNetInterface::_GBVssDeviceCommPtr p(__uuidof   (GBVssNetInterface::GBVssDeviceComm));
         pNetInterface = p;
         __int64 pLuns;
         pNetInterface->GetAllVisableLuns(&size, (LONG*)&pLuns);
         // Blows up
         return 0;
    // Managed object
    namespace GBVssNetInterface
        public interface _GBVssDeviceComm
            //unsafe int GetAllVisableLuns(int* size, char* pLunBuffer);
            unsafe int GetAllVisableLuns(ref int size, ref Int64 pLunBuffer);
        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;

Share This Page