Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I have a native c++ code with structure as follows:
C#
typedef struct
{
  
  unsigned long ProtocolID;
  unsigned long RxStatus;
  unsigned long TxFlags;
  unsigned long Timestamp;
  unsigned long DataSize;
  unsigned long ExtraDataIndex;
  BYTE Data[4128];
} PASSTHRU_MSG;


I 'm trying to write a wrapper in c++/CLI , so i have defined structure as follows:

[StructLayout(LayoutKind::Sequential)]
C#
ref struct PASSTHRU_MSG_X
    {

       PASSTHRU_MSG_X()
       {
            this->data = gcnew array<byte>(4128);

       }

      UInt32 ProtocolID;
      UInt32 RxStatus;
      UInt32 TxFlags;
      UInt32 Timestamp;
      UInt32 DataSize;
      UInt32 ExtraDataIndex;
      array<BYTE> ^data;

    } ;



Now I have a function like this:

C#
long CPassThruWrapper::PassThruReadMsgs(UInt32 channelId, array<PASSTHRU_MSG_X^> ^ respMsgs, UInt32 &numResponses, UInt32  timeout)
{   
    PASSTHRU_MSG* responses = new PASSTHRU_MSG[respMsgs->Length];
    int n = respMsgs->Length;
    unsigned long numResp;

    //This is native call>> where I get array of structure PASSTHRU_MSG in responses
    long val = NativePassThruReadMsgs(channelId, responses, &numResp, timeout);    

    for (int i=0;i<1;i++)
    {
        // Here my function throws exception saying attempted to read /write memory which is    write protected 
        PASSTHRU_MSG_X ^msg = static_cast<PASSTHRU_MSG_X^>(Marshal::PtrToStructure(IntPtr(&responses[i]), PASSTHRU_MSG_X::typeid));
    }    

    return val;

}


Here I'm trying to convert responses which is an array of native structure PASSTHRU_MSG and just tried to marshal first structure element to managed strcture PASSTHRU_MSG_X.
When i tried this: It threw exception:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Please note I tried same code by commenting byte array in both structures and it worked without any problem.
Can somebody help me in pointing mistake I'm doing in declaring byte array inside that structure so that this code works properly.
Thanks in advance
Posted
Updated 23-May-13 3:50am
v2

1 solution

I found solution for this:

I changed managed structure like this and it worked!!

C#
[StructLayout(LayoutKind::Sequential)]
    ref struct PASSTHRU_MSG_X
        {
          UInt32 ProtocolID;
          UInt32 RxStatus;
          UInt32 TxFlags;
          UInt32 Timestamp;
          UInt32 DataSize;
          UInt32 ExtraDataIndex;
          [MarshalAs(UnmanagedType::ByValArray, SizeConst = 4128)]
          array<BYTE>^ data;
        } ;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900