gpt4 book ai didi

c# - 当参数之一为 void* 时,如何在 C# 中使用 C 函数?

转载 作者:行者123 更新时间:2023-11-30 17:29:57 25 4
gpt4 key购买 nike

我有一个执行以下功能的 C 代码:

int Read (DWORD Address, DWORD NoOfBytes, int UnitSize, void* Buffer);

当缓冲区被来自该地址的数据填充时。函数的返回值为 1 或 0,表示成功或失败。

我尝试执行的 C# 代码是:

private const string LibName = "Test.dll";
[DllImport(LibName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int Read([System.Runtime.InteropServices.MarshalAs(UnmanagedType.I4), In] int Address, int NoOfBytes,
int UnitSize, [System.Runtime.InteropServices.MarshalAs(UnmanagedType.AsAny), Out] Object Buffer);

我通过以下方式使用此功能:

var resultBuf = new short[40];
int returnValue = Read(parsedAddress, size, 2, resultBuf);

但结果是缓冲区仍然是 40 个零的缓冲区。

知道如何完成这项工作吗?我做错了什么??

更多详情:C 函数完美运行。发生的最奇怪的事情是,在 C# 上,我得到的响应不是在缓冲区中,而是在返回值中(而不是返回 0 或 1,而是以 int 形式返回值)

最佳答案

大多数情况下,在使用 DLL 互操作时,您应该使用 IntPtr。最重要的是,您甚至不需要“out”参数。 :)

如果您打算仅在字节数组等上使用该函数,您当然可以使用例如 byte* 而不是 void*,但应该使用前面的方法。

public static extern int Read(uint Address, uint NoOfBytes, int UnitSize, IntPtr buffer)

这样应该就可以了。

还请记住,DLL 导入是一项成本高昂的操作,应该避免,例如,“读取”操作可以在纯 C# 中的不安全代码中实现,并且可能会执行得更好(尽管差异可以忽略不计)在这种情况下微不足道)。

关于c# - 当参数之一为 void* 时,如何在 C# 中使用 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25422347/

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