开发者

Could accessing a variable directly (rather than with a pointer and dereferecer) give different values?

I know it's an odd question and I risk showing my greenness, but I'm tearing my hair out here.

I have a C++ example that works as expected. Here's a snippet of the bothersome bit:

BIRDFRAME frame;
birdGetMostRecentFrame(GROUP_ID,&frame);
BIRDREADING *bird_data;
bird_time=frame.dwTime;
for(FBBloop=FBBstart; FBBloop<FBBend; FBBloop++ )
{                开发者_JS百科   
    bird_data = &frame.reading[FBBloop];
    // Do stuff
}

Note that bird_data is a pointer and is assigned the address of frame.reading[FBBloop]. My app is written in C# and so doesn't have any of this pointer malarkey. The corresponding bit looks like this:

FlockOfBirds.BIRDFRAME frame = new FlockOfBirds.BIRDFRAME();
FlockOfBirds.birdGetMostRecentFrame(1, ref frame);
Console.WriteLine("T:{0}",frame.dwTime.ToString());
FlockOfBirds.BIRDREADING reading;
for (int k = 1; k <= sysconf.byNumDevices; k++)
{
    reading = frame.readings[k];
    Console.WriteLine("  [{0}][{1}][{2}]", reading.position.nX.ToString(), reading.position.nY.ToString(), reading.position.nZ.ToString());
}

The problem is that in the C# example, only reading[1] has meaningful data. In the C++ example both bird_data[1] and bird_data[2] have good data. Oddly, reading[2-n] don't all have zeroed values, but appear to be random and constant. Here's what the output from the C# app looks like:

T:17291325
  [30708][-2584][-5220]
  [-19660][1048][-31310]

T:17291334
  [30464][-2588][-5600]
  [-19660][1048][-31310]

T:17291346
  [30228][-2600][-5952]
  [-19660][1048][-31310]

T:17291354
  [30120][-2520][-6264]
  [-19660][1048][-31310]

T:17291363
  [30072][-2388][-6600]
  [-19660][1048][-31310]

Notice that the top triplet of each entry is slightly different from those of the entries pre- and succeeding it. In the C++ app, the bottom line behaves similarly, but here it stays the same throughout.

Could this be to do with the lack of pointing and dereferencing? Or am I barking up entirely the wrong tree? Have I done something else that's obviously stupid? Most importantly: how do I make it work?


Update: Structs & externs

C++

// Bird reading structure
typedef struct tagBIRDREADING
{
    BIRDPOSITION    position;   // position of receiver
    BIRDANGLES      angles;     // orientation of receiver, as angles
    BIRDMATRIX      matrix;     // orientation of receiver, as matrix
    BIRDQUATERNION  quaternion; // orientation of receiver, as quaternion
    WORD            wButtons;   // button states
}
BIRDREADING;

// Bird frame structure
//
// NOTE: In stand-alone mode, the bird reading is stored in reading[0], and
//  all other array elements are unused.  In master/slave mode, the "reading"
//  array is indexed by bird number - for example, bird #1 is at reading[1],
//  bird #2 is at reading[2], etc., and reading[0] is unused.
typedef struct tagBIRDFRAME
{
    DWORD           dwTime;     // time at which readings were taken, in msecs
    BIRDREADING     reading[BIRD_MAX_DEVICE_NUM + 1];  // reading from each bird
}
BIRDFRAME;

BOOL DLLEXPORT birdGetMostRecentFrame(int nGroupID, BIRDFRAME *pframe);

C#:

[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct BIRDREADING
{
        public BIRDPOSITION position;
        public BIRDANGLES angles;
        public BIRDMATRIX matrix;
        public BIRDQUATERNION quaternion;
        public ushort wButtons;
}

[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct BIRDFRAME
{
        public uint dwTime;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 127)]
        public BIRDREADING[] readings;
}

[DllImport(@"Bird.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern bool birdGetMostRecentFrame(int nGroupID, ref BIRDFRAME frame);

** Update 2: More structs: **

C++

#pragma pack(1) // pack the following structures on one-byte boundaries

// Bird position structure
typedef struct tagBIRDPOSITION
{
    short   nX;         // x-coordinate
    short   nY;         // y-coordinate
    short   nZ;         // z-coordinate
}
BIRDPOSITION;

// Bird angles structure
typedef struct tagBIRDANGLES
{
    short   nAzimuth;   // azimuth angle
    short   nElevation; // elevation angle
    short   nRoll;      // roll angle
}
BIRDANGLES;

// Bird matrix structure
typedef struct tagBIRDMATRIX
{
    short   n[3][3];    // array of matrix elements
}
BIRDMATRIX;

// Bird quaternion structure
typedef struct tagBIRDQUATERNION
{
    short   nQ0;        // q0
    short   nQ1;        // q1
    short   nQ2;        // q2
    short   nQ3;        // q3
}
BIRDQUATERNION;

#pragma pack()  // resume normal packing of structures

C#

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDPOSITION
{
    public short nX;
    public short nY;
    public short nZ;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDANGLES
{
    public short nAzimuth;  // azimuth angle
    public short nElevation;    // elevation angle
    public short nRoll;     // roll angle
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct BIRDMATRIX
{
    public fixed short n[9];
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDQUATERNION
{
    public short nQ0;       // q0
    public short nQ1;       // q1
    public short nQ2;       // q2
    public short nQ3;       // q3
}


I tried your struct in two projects (C++/C#) and it seems to work correctly.

I use this in C++:

#include "stdafx.h"
#include "windows.h"

#pragma pack(1) // pack the following structures on one-byte boundaries

// Bird position structure
typedef struct tagBIRDPOSITION
{
    short   nX;         // x-coordinate
    short   nY;         // y-coordinate
    short   nZ;         // z-coordinate
}
BIRDPOSITION;

// Bird angles structure
typedef struct tagBIRDANGLES
{
    short   nAzimuth;   // azimuth angle
    short   nElevation; // elevation angle
    short   nRoll;      // roll angle
}
BIRDANGLES;

// Bird matrix structure
typedef struct tagBIRDMATRIX
{
    short   n[3][3];    // array of matrix elements
}
BIRDMATRIX;

// Bird quaternion structure
typedef struct tagBIRDQUATERNION
{
    short   nQ0;        // q0
    short   nQ1;        // q1
    short   nQ2;        // q2
    short   nQ3;        // q3
}
BIRDQUATERNION;

#pragma pack()  // resume normal packing of structures

typedef struct tagBIRDREADING
{
    BIRDPOSITION    position;   // position of receiver
    BIRDANGLES      angles;     // orientation of receiver, as angles
    BIRDMATRIX      matrix;     // orientation of receiver, as matrix
    BIRDQUATERNION  quaternion; // orientation of receiver, as quaternion
    WORD            wButtons;   // button states
}
BIRDREADING;

#define BIRD_MAX_DEVICE_NUM 126

// Bird frame structure
//
// NOTE: In stand-alone mode, the bird reading is stored in reading[0], and
//  all other array elements are unused.  In master/slave mode, the "reading"
//  array is indexed by bird number - for example, bird #1 is at reading[1],
//  bird #2 is at reading[2], etc., and reading[0] is unused.
typedef struct tagBIRDFRAME
{
    DWORD           dwTime;     // time at which readings were taken, in msecs
    BIRDREADING     reading[BIRD_MAX_DEVICE_NUM + 1];  // reading from each bird
}
BIRDFRAME;

extern "C" __declspec( dllexport ) BOOL birdGetMostRecentFrame(int nGroupID, BIRDFRAME *pframe) {

    pframe->dwTime = GetTickCount();
    for (int i = 0; i < sizeof(pframe->reading)/sizeof(*pframe->reading); i++) {
        pframe->reading[i] = BIRDREADING();
        pframe->reading[i].position.nX = (short)i;
        pframe->reading[i].position.nY = (short)i + 1;
        pframe->reading[i].position.nZ = (short)i + 2;
    }
    return TRUE;
}

And this in C#:

   [StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDPOSITION
{
    public short nX;
    public short nY;
    public short nZ;
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDANGLES
{
    public short nAzimuth;  // azimuth angle
    public short nElevation;    // elevation angle
    public short nRoll;     // roll angle
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct BIRDMATRIX
{
    public fixed short n[9];
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BIRDQUATERNION
{
    public short nQ0;       // q0
    public short nQ1;       // q1
    public short nQ2;       // q2
    public short nQ3;       // q3
}

    [StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct BIRDREADING
{
        public BIRDPOSITION position;
        public BIRDANGLES angles;
        public BIRDMATRIX matrix;
        public BIRDQUATERNION quaternion;
        public ushort wButtons;
}

[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct BIRDFRAME
{
        public uint dwTime;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 127)]
        public BIRDREADING[] readings;
}

    public partial class Form1 : Form
    {
        [DllImport(@"Bird.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool birdGetMostRecentFrame(int nGroupID, ref BIRDFRAME frame);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BIRDFRAME bf = new BIRDFRAME();

            if (checkBox1.Checked)
            {                
                bf.readings = new BIRDREADING[127];
            }

            if (birdGetMostRecentFrame(0, ref bf)) {
                listBox1.Items.Add(bf.dwTime.ToString());
                Console.WriteLine(bf.dwTime.ToString());
                for (int k = 1; k <= 3; k++)
                {
                    var reading = bf.readings[k];
                    Console.WriteLine(String.Format("  [{0}][{1}][{2}]", reading.position.nX.ToString(), reading.position.nY.ToString(), reading.position.nZ.ToString()));
                    listBox1.Items.Add(String.Format("  [{0}][{1}][{2}]", reading.position.nX.ToString(), reading.position.nY.ToString(), reading.position.nZ.ToString()));
                }
            }
        }
    }

In both cases (reading initialized as new in C#, or not it gives back meaningful data:

40067905
  [1][2][3]
  [2][3][4]
  [3][4][5]
40068653
  [1][2][3]
  [2][3][4]
  [3][4][5]
40069418
  [1][2][3]
  [2][3][4]
  [3][4][5]
40072585
  [1][2][3]
  [2][3][4]
  [3][4][5]

Did it on Windows7 64 bit. I'm attaching a ZIP with both projects for VS2010.

Here is the link:

http://hotfile.com/dl/115296617/9644496/testCS.zip.html

It seems that you are setting wrong values inside that position struct :/


It seems that sysconf.byNumDevices == 1 so i <= sysconf.byNumDevices loops only once and you are reading uninitialized memory segments.

Try printing out sysconf.byNumDevices, and if it is 1 try to trace that issue.


Arrays in .NET are zero based, not one based. Could that be it? Of course, .NET also has strict bounds checking so I would have expected your "last" access to the array to fail with an exception too.

Without having access to FlockOfBirds source, I am not sure what else to tell you.


Just a thought: do you actually need the ref when passing to your method?

FlockOfBirds.BIRDFRAME frame = new FlockOfBirds.BIRDFRAME();
FlockOfBirds.birdGetMostRecentFrame(1, ref frame);

If I'm not mistaken then in c# all classes are passed by reference anyway. I might be mad but aren't you passing a ref to a ref?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜