gpt4 book ai didi

c# - 如何将 native C++ 内存转换为 C# 结构?

转载 作者:太空狗 更新时间:2023-10-29 20:28:42 26 4
gpt4 key购买 nike

我在 C++ 中有以下 native 函数接口(interface):

int func1(void* param, int sizeOfParam).

在文档中提供了以下调用示例:

typedef struct
{
int x;
int y;
int width;
int height;
} Rect;

Rect rect;

int func1((void*)&rect, sizeof(rect));

我需要从 C# 代码调用这个函数。

native 库的开发人员在 C# 中提供了以下 header :

[DllImport(NATIVE_DLL_NAME, 
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "func1")]
private static extern int func1(IntPtr param, int sizeOfParam);

我还有以下 C# 结构Rect:

public struct Rect
{
int x;
int y;
int width;
int height;
};

我需要在 C# 代码中调用 func1 并传递 Rect:

我做了以下事情:

Rect rect = new Rect();
int rectSize = System.Runtime.InteropServices.Marshal.SizeOf(rect);

func1(???, rectSize);

??? 的位置应该放置什么 rect 应该传递(但由于类型不兼容而不可能)?

看来应该传IntPtr,然后转为struct rect。如何实现?

(rect这里是输出参数)

更新:

不希望更改 C++ 代码和 C# 包装器的签名 - 它是第三方代码。
此外,Rect 的变量并不总是作为 func1

的第一个参数传递

最佳答案

您更改了游戏规则以禁止修改 C# 代码。因此 P/invoke 必须是这种形式:

private static extern int func1(IntPtr param, int sizeOfParam);

在这种情况下,您需要手动进行编码:

int size = Marshal.SizeOf(typeof(Rect));
IntPtr param1 = Marshal.AllocHGlobal(size);
try
{
func1(param1, size);
Rect rect = (Rect)Marshal.PtrToStructure(param1, typeof(Rect));
}
finally
{
Marshal.FreeHGlobal(param1);
}

关于c# - 如何将 native C++ 内存转换为 C# 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7633794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com