我在让代码在托管环境中运行时遇到问题(VS2008 C ++ / CLI Win Forms应用程序)。问题是我无法在托管代码中声明非托管结构(甚至可能?),所以我已经声明了一个托管结构但现在我遇到了一个问题如何从中复制字节缓冲到该结构。这是纯粹的C ++代码,显然可以按预期工作:
typedef struct GPS_point {
float point_unknown_1;
float latitude;
float longitude;
float altitude; // x10000
float time;
int point_unknown_2;
int speed; // x100
int manually_logged_point; // flag (1 --> point logged manually)
} track_point;
int offset = 0;
int filesize = 256; // simulates filesize
int point_num = 10; // simulates number of records
int main () {
char *buffer_dyn = new char[filesize]; // allocate RAM
// here, the file would have been read into the buffer
buffer_dyn[0xa8] = 0x1e; // simulates the speed data (1e 00 00 00)
buffer_dyn[0xa9] = 0x00;
buffer_dyn[0xaa] = 0x00;
buffer_dyn[0xab] = 0x00;
offset = 0x90; // if the data with this offset is transfered trom buffer
// to struct, int speed is alligned with the buffer at the
// offset of 0xa8
track_point *points = new track_point[point_num];
points[0].speed = 0xff; // (debug) it should change into 0x1e
memcpy(&points[0],buffer_dyn+offset,32);
cout << "offset: " << offset << "\r\n";
//cout << "speed: " << points[0].speed << "\r\n";
printf ("speed : 0x%x\r\n",points[0].speed);
printf("byte at offset 0xa8: 0x%x\r\n",(unsigned char)buffer_dyn[0xa8]); // should be 0x1e
delete[] buffer_dyn; // release RAM
delete[] points;
/*
What I need is to rewrite the lines 29 and 31 to work in the managed code (VS2008 Win Forms C++/CLI)
What should I have after:
array<track_point^>^ points = gcnew array<track_point^>(point_num);
so I can copy 32 bytes from buffer_dyn to the managed struct declared as
typedef ref struct GPS_point {
float point_unknown_1;
float latitude;
float longitude;
float altitude; // x10000
float time;
int point_unknown_2;
int speed; // x100
int manually_logged_point; // flag (1 --> point logged manually)
} track_point;
*/
return 0;
}
这是paste to codepad.org所以可以看到代码没问题。
我需要的是重写这两行:
track_point *points = new track_point[point_num];
memcpy(&points[0],buffer_dyn+offset,32);
可以在托管应用程序中运行。我写道:
array<track_point^>^ points = gcnew array<track_point^>(point_num);
现在我正在尝试重现所描述的从缓冲区复制数据的结构,但不知道应该怎么做。
或者,如果有一种方法可以按照我的代码中显示的相同方式使用非托管结构,那么我希望避免使用托管结构。