How can i send a ref pointer to a function and return an address to an allocated memory, in C#. The following code doesn't compile:
class Test
{
public byte [] byteArr_1 = new byte [1024];
//public byte* P_byte;
public unsafe void SetAddress(ref byte* p_b)
{
p_b = &byteArr_1[0];
}
}
This is the error i receive:
You can only take the address of an unfixed expression inside of a fixed statement initializer
Originally i was using a usb transmit dll that received and initialized a *byte pointer for a buffer when the connection was established. Now i would like to change that dll with a different platform with minimum changes in code, so i need to initializer the buffer myself.
Thanks,
If the unmanaged code you are calling requires a pointer to the buffer for a long time then you do not want to be passing a managed buffer in the first place. Why? Because the managed buffer then has to be pinned for a long time, and that makes the garbage collector do extra work.
Instead, allocate an unmanaged buffer with an unmanaged memory allocator, and pass a pointer to that to the unmanaged code.
As noted, you can pin an object with the fixed statement, but this will not work for you because you are returning the pointer via a ref parameter. If you tried to use the fixed statement, the code would compile, but the resulting pointer might be invalid by the time it is used. This is because once the fixed statement block is exited, the object is unpinned, which allows its address to change at any time.
In this case, you will need to pin the buffer by using GCHandle.Alloc:
class Test
{
public byte [] byteArr_1 = new byte [1024];
private GCHandle pinned;
//public byte* P_byte;
public unsafe void SetAddress(ref byte* p_b)
{
pinned = GCHandle.Alloc(byteArr_1, GCHandleType.Pinned);
p_b = (byte*)pinned.AddrOfPinnedObject();
// NOTE: Don't forget to free the GCHandle at some point via GCHandle.Free!
// Remember that once this handle is freed, the pointer should not be used in any way.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With