3

このコードに問題があります:

//Creating a new ImageElement Struct
ImageElement oElement = new UM0516.ImageElement();
//Create a pointer and allocate enough room for the struct type
IntPtr pElement = Marshal.AllocHGlobal(Marshal.SizeOf(new UM0516.ImageElement()));
//Copy the contents of the struct into the allocated memory space
Marshal.StructureToPtr(oElement, pElement, true);
//Function that takes a file pointed to by handle, and does some sweet sweet things
//And returns a loaded struct pointed to by pElement
FILES_GetImageElement(handle, el, out pElement);

ここで混乱します。コードをステップ実行して、最後の関数 (pElement が指すメモリ内のビットを変更する必要があります) を呼び出した後、oElement が変更されたことを確認します!? Marshal.StructureToPtr は、管理された構造体からメモリにデータを「コピー」すると思いました。では、2 つの場所は実際には同じでしょうか。管理された構造体 oElement と、pElement が指す割り当てられたメモリ?

4

2 に答える 2

3

この記事で詳しく説明します。

書式設定されたblittableクラスは、マネージド メモリとアンマネージド メモリの両方で固定レイアウト (書式設定済み) と共通データ表現を持ちます。これらの型がマーシャリングを必要とする場合、ヒープ内のオブジェクトへのポインターが呼び出し先に直接渡されます。呼び出し先は、ポインタによって参照されているメモリ位置の内容を変更できます。

于 2009-04-09T21:32:20.737 に答える
0

おそらく、構造体を手動でポインターにマーシャリングする必要はないと思います。構造体のマネージ バージョンがアンマネージ構造体のレイアウトと一致する限り、相互運用マーシャラーがマーシャリングを処理します。

pElement を完全に取り除き、oElement を ref パラメーター (途中で何が入っているかを気にする場合) または out パラメーターとして渡すことができるはずです。

于 2009-04-09T21:30:15.093 に答える