gc[] to gc* conversion

N

Nanditha Chandra

Hi!

I am new to managed c++. I have a byte gc array and I want to pass it
to a function that takes a __gc* to unsigned char. How would I convert
my byte array to this?

Byte arBuf[] = __gc new Byte[nSize];

// I have code here to read from a file to this buffer.
// Now I need to pass this to a function which is defined as follows:

void Write(unsigned char __gc*);

How can I convert my byte array to unsigned char __gc*?

Thanks,
D
 
B

Brandon Bray [MSFT]

Nanditha said:
How can I convert my byte array to unsigned char __gc*?

Take the address of the first array element. For example:

void F(unsigned char __gc* p) {}

Byte arr[] = new Byte[10];
F(&arr[0]);

Cheerio!
 
N

Nanditha Chandra

Brandon Bray said:
Take the address of the first array element. For example:

void F(unsigned char __gc* p) {}

Byte arr[] = new Byte[10];
F(&arr[0]);

Can you do that? I thought contiguious allocation is not guaranteed.
So, in Foo, Can I assume that the next 10 bytes is what I want.

Thanks,
D
 
B

Brandon Bray [MSFT]

Nanditha said:
Can you do that? I thought contiguious allocation is not guaranteed.
So, in Foo, Can I assume that the next 10 bytes is what I want.

Yes. Arrays are guaranteed to have contiguous allocation. Other than using
ExplicitLayout, arrays are the only way to get contiguous allocation.
 
W

Wild Wind

Brandon said:
Nanditha said:
How can I convert my byte array to unsigned char __gc*?

Take the address of the first array element. For example:

void F(unsigned char __gc* p) {}

Byte arr[] = new Byte[10];
F(&arr[0]);

Cheerio!

Brandon,

Just wondering... do you not have to pin the &arr[0]
address before passing it to the F function, since arr
is managed and can be shifted around?
 
B

Brandon Bray [MSFT]

Wild said:
void F(unsigned char __gc* p) {}

Byte arr[] = new Byte[10];
F(&arr[0]);

Just wondering... do you not have to pin the &arr[0]
address before passing it to the F function, since arr
is managed and can be shifted around?

Because the argument to F used __gc to qualify the pointer, it notes that
the garbage collector is going to track this pointer and update it if the
memory gets moved around.

Now, if __gc hadn't been there (or if the __nogc keyword were used), then
the pointer would not be tracked by the garbage collector. This allows the
pointer to be used by native code. In that situation, you are correct that
the pointer needs to be pinned first.

Hope that makes sense. Cheerio!
 

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