pinning pointer problem

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;
}
};
 
D

Doug Harrison [MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top