pinning pointer problem

  • Thread starter Thread starter demofo
  • Start date Start date
D

demofo

Does the pinning pointer safe?since the Read function will change the
ppBuffer points to unmanaged C++ heap,how does the dot net runtime knows
they will not move the allocated memory (pointed by ppBuffer)during the
garbage collection?

class NonGCClass
{
private:
int GetBufferLength()
{
return rand();
}
public:
int Read(unsigned char **ppBuffer)
{
const int bufferLength=GetBufferLength();
*ppBuffer=new unsigned char[bufferLength];
memset(*ppBuffer,0x64,bufferLength);
return bufferLength;
}
};
__gc class GCClass
{
private:
NonGCClass *m_pNonGC;
public:
GCClass()
:m_pNonGC(new NonGCClass())
{
unsigned char *pBuffer=NULL;
unsigned char __pin *pPinBuffer=pBuffer;

const int bufferLength=m_pNonGC->Read(&pBuffer);

Byte byteArray[] = new Byte[bufferLength];
Marshal::Copy((IntPtr)pBuffer,byteArray,0,bufferLength);

delete []pBuffer;

pBuffer=NULL;
pPinBuffer=NULL;
}
};
 
demofo said:
Does the pinning pointer safe?since the Read function will change the
ppBuffer points to unmanaged C++ heap,how does the dot net runtime knows
they will not move the allocated memory (pointed by ppBuffer)during the
garbage collection?

class NonGCClass
{
private:
int GetBufferLength()
{
return rand();
}
public:
int Read(unsigned char **ppBuffer)
{
const int bufferLength=GetBufferLength();
*ppBuffer=new unsigned char[bufferLength];
memset(*ppBuffer,0x64,bufferLength);
return bufferLength;
}
};
__gc class GCClass
{
private:
NonGCClass *m_pNonGC;
public:
GCClass()
:m_pNonGC(new NonGCClass())
{
unsigned char *pBuffer=NULL;
unsigned char __pin *pPinBuffer=pBuffer;

const int bufferLength=m_pNonGC->Read(&pBuffer);

Byte byteArray[] = new Byte[bufferLength];
Marshal::Copy((IntPtr)pBuffer,byteArray,0,bufferLength);

delete []pBuffer;

pBuffer=NULL;
pPinBuffer=NULL;
}
};

I'm not quite sure what you're asking, but a pinning pointer pins the thing
pointed to, not the pointer used to initialize it. Above, pinning pBuffer
accomplishes nothing, as it is an unmanaged pointer. There is no problem
with your use of your Read function. It simply stores an unsigned char* in
another unsigned char*. If you were dealing with __gc pointers all around,
it would be no problem to overwrite one with the other; the pinning pointer
would be unaffected by this.
 
Back
Top