System access violation in C to C# interop code RRS feed

  • Question

  • Hello,
    I am attempting to use a C function through C# Interop and I am receiving an access violation on one function.  I have tried a number of things and I can't seem to solve this.

    Here is the C code that needs to be changed into c# code:

    typedef struct
      char SerNo[64];

      unsigned char hwVer; 

      HANDLE device; // Set by the API on return from SelectDevice()

    } DeviceT;

    This struct is used by the following function:

            error = GetDevices(DeviceT *devices, unsigned int *numDevs, unsigned int maxDevs)

    There is one other function in the C code:

            error = SelectDevice(DeviceT *device)

    So I began by defining DeviceT.  I tried a few ways, but settled on this since it is simple:


            public struct DeviceT
                [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)]
                public string SerNo;

                public byte hwVer;
                public IntPtr device;

    The GetDevices function was set to this:

            [DllImport("file.dll", CallingConvention = CallingConvention.Cdecl)]
            public unsafe static extern  ErrT GetDevices([In, Out] DeviceT[] devices, uint* numDevs, uint maxDev);

    The SelectDevices function was set to this:

             [DllImport("file.dll", CallingConvention = CallingConvention.Cdecl)]
            public unsafe static extern ErrT SelectDevice([In, Out] DeviceT devices);

    The code goes like this:

               uint numDevs = 6;
               uint maxDev = 6;
       uint chosenIdx = 0;

       DeviceT[] devices = new DeviceT[6];

               err = GetDevices(devices, &NumberOfDevices, maxDev))

    At this point everything is correct.  The devices array has the correct information in it.

    I now continue with (I just hard code select the first device)

               chosenIdx = 0;

               var chosenDevice = devices[chosenIdx];

               err = SelectDevice(chosenDevice);

    This last function returns a System.Access Violation

    I tried a whole bunch of things but all end up with the same result.  I suspect it has something to do with the HANDLE but I am not sure.
    Thanks for any help.

    Saturday, January 18, 2020 9:15 PM

All replies

  • Check out StructLayoutAttribute.Pack (C#) and #pragma pack (C++) on MSDN. Visual C++ default packing is different for x86 and x64 (see /Zp compiler option). And you may have #pragma pack code to change the default pack size. 

    Visual C++ MVP

    Sunday, January 19, 2020 1:02 AM
  • Hi,

    Thanks.  Unfortunately none of them work.  I tried 2, 4, 8, 16,32,64.

    Sunday, January 19, 2020 4:50 PM
  • Pack size could be 1 too. But use the value from #pragma pack(show). 

    Visual C++ MVP

    Tuesday, January 21, 2020 12:15 AM