Managed Byte[] array to Native

  c++, c++-cli, marshalling

Is there a better way or cleaner way to do this:

pin_ptr<Byte> p = &bytes[0];

The code seems to work okay.
I am using Visual Studio 2008 / 2010. The project can not be converted to later frameworks. The commented line of code is the C++ Native method signature. This project is a C++ CLI / .dll managed. The library is exposing MicroChip’s Native C++ library code to C# Clients.

public ref class Mc2221a : IDisposable
{
 public: 
  Int32 Mc2221a::I2cWrite(UInt32 bytesToWrite, Byte slaveAddress, Byte use7bitAddress, array<Byte> ^bytes)
  {
   pin_ptr<Byte> p = &bytes[0];
   unsigned char *i2cTxData = p;
   // Mcp2221_I2cWrite(void* handle, unsigned int bytesToWrite, unsigned char slaveAddress, unsigned char use7bitAddress, unsigned char* i2cTxData);
   Int32 rv = Mcp2221_I2cWrite(handle, bytesToWrite, slaveAddress, use7bitAddress, i2cTxData);
   return rv;           
  }
}

Source: Windows Questions C++

LEAVE A COMMENT