using pin_ptr with a whole pointer

G

Guest

I could not get the following code to compile:
public ref class wrapper
{
void Read(int^ mpLen)
{
pin_ptr<int> pLen = mpLen;
unmanaged* punman = new unmanaged();
punman->Read(pLen);
return;
}
}
The error was in the conversion from a managed pointer, mpLen, to
pin_ptr<int>.

When I changed the code by wrapping the int in a managed class, it worked:
public ref class BytesRead
{
public:
int Len;
};
public ref class wrapper
{
void Read(BytesRead^ mpBR)
{
pin_ptr<int> pLen = &mpBR->Len;
unmanaged* punman = new unmanaged();
punman->Read(pLen);
return;
}
}

I interpret that difference as pin_ptr being happy with an interior pointer
but not a whole pointer. But surely there is a way to pin the whole pointer
to a managed class. What did I do wrong?

Thanks in advance,
Ray
 
H

Holger Grund

T Ray Humphrey said:
I could not get the following code to compile:
public ref class wrapper
{
void Read(int^ mpLen)
{
pin_ptr<int> pLen = mpLen;
unmanaged* punman = new unmanaged();
punman->Read(pLen);
return;
}
}
The error was in the conversion from a managed pointer, mpLen, to
pin_ptr<int>.

int^ is not what the CLR calls a managed pointer. It's rather the boxed form
of an int (there's no representation in C# & VB).

So first of all, it is probably not the interface you want. You'd rather
want
interior_ptr<int> or int% which both translate to managed pointers (int&
in ILASM speak or ref/out in C#)

If you really want that interface, I think you should be able to use
&*mpLen.
However, IIRC the CLI standard did not guarantee that unbox gives you
a pointer to the original object (even though I fail to understand, why that
is).
I interpret that difference as pin_ptr being happy with an interior
pointer
but not a whole pointer. But surely there is a way to pin the whole
pointer
to a managed class. What did I do wrong?
R% and R^ are the same thing for the CLR (only C++ language semantics are
different). V% and V^ are different. The first one is a managed pointer
(V& in ILASM), the second one is the boxed representation with C++
pointer semantics.
interior_ptr<V> yields the same CLR type as V%. They only differ in
source-level semantics (and only for C++/CLI).

-hg
 
G

Guest

Thanks a bunch! That fixed it.
I changed the int^ to an int%. I was still able to do the pin with:
pin_ptr<int> p = &i;
Thanks, too, for your detailed explanation. It help a lot.
 

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