[在使用pinvoke时如何将指针传递给指针参数? [重复]

问题描述 投票:0回答:1

有一个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的值是错误的。我应该如何解决我的问题?

c# .net pinvoke dllimport
1个回答
0
投票

此行应使用new_item_ptr,而不是dev

IntPtr oneDeep = (IntPtr)Marshal.PtrToStructure(new_item_ptr, typeof(IntPtr));
© www.soinside.com 2019 - 2024. All rights reserved.