有一个C代码。我想用PInvoke将其包装在C#中。
struct Item {
int color;
int shape;
};
UINT8 get_item(struct Item** i) {
*i = (struct Item*) malloc(sizeof(struct Item));
if(*i != NULL) return 0;
else return 1;
}
和以下C#代码
[DllImport("sample.dll", EntryPoint = "get_item")]
public static extern Byte get_item(out IntPtr ptr);
static void Main(string[] args)
{
IntPtr new_item_ptr;
get_item(out new_item_ptr);
IntPtr oneDeep = (IntPtr)Marshal.PtrToStructure(new_item_ptr, typeof(IntPtr));
Item out_item = (Item )Marshal.PtrToStructure(oneDeep, typeof(Item));
Console.ReadKey();
}
我发现out_item的值是错误的。我应该如何解决我的问题?
此行应使用new_item_ptr,而不是dev
IntPtr oneDeep = (IntPtr)Marshal.PtrToStructure(new_item_ptr, typeof(IntPtr));