可以直接访问变量(而不是使用指针和dereferecer)给出不同的值?

时间:2011-04-15 19:50:25

标签: c# c++ pointers

我知道这是一个奇怪的问题,我冒着露出绿色的风险,但我在这里撕扯我的头发。

我有一个按预期工作的C ++示例。这是令人讨厌的一点:

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

请注意,bird_data是一个指针,并被指定为frame.reading[FBBloop]的地址。我的应用程序是用C#编写的,所以没有任何这个指针malarkey。相应的位看起来像这样:

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());
}

问题在于,在C#示例中,只有reading[1]具有有意义的数据。在C ++示例中,bird_data[1]bird_data[2]都有良好的数据。奇怪的是,reading[2-n]并非所有值都归零,但似乎是随机且不变的。以下是C#app的输出结果:

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]

请注意,每个条目的顶部三元组与之前和之后的条目略有不同。在C ++应用程序中,底线表现相似,但在此始终保持不变。

这可能与缺乏指向和解除引用有关吗?还是我完全吠叫错了树?我做过其他明显愚蠢的事吗?最重要的是:我如何让它发挥作用?


更新:Structs&amp;实习医生

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);

**更新2:更多结构:**

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
}

4 个答案:

答案 0 :(得分:1)

我在两个项目(C ++ / C#)中尝试了你的结构,它似乎工作正常。

我在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;
}

这在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()));
                }
            }
        }
    }

在这两种情况下(读取在C#中初始化为新的,否则它会返回有意义的数据:

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]

在Windows7 64位上做了吗? 我正在为VS2010添加两个项目的ZIP。

这是链接:

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

您似乎在该位置struct:/

中设置了错误的值

答案 1 :(得分:0)

似乎sysconf.byNumDevices == 1所以i <= sysconf.byNumDevices只循环一次而你正在读取未初始化的内存段。

尝试打印sysconf.byNumDevices,如果是1,请尝试跟踪该问题。

答案 2 :(得分:0)

.NET中的数组基于零,而不是基于数组。可能是吗?当然,.NET也有严格的边界检查,所以我原本期望你对数组的“最后”访问也会失败,也会出现异常。

无法访问FlockOfBirds来源,我不确定还能告诉您什么。

答案 3 :(得分:0)

只是一个想法:转到你的方法时你真的需要参考吗?

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

如果我没有弄错,那么在c#中,无论如何都会通过引用传递所有类。我可能会生气,但你不是把裁判传给裁判?