gpt4 book ai didi

C# 函数不更新 SAFEARRAY

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:01 25 4
gpt4 key购买 nike

我有一个具有以下签名的 C# 函数:

int Get1251Bytes(string source, byte[] result, Int32 lengthOfResult)

我从 C++ 调用它。编译器通知我第二个参数必须具有 SAFEARRAY* 类型。所以我这样调用它:

SAFEARRAY* safeArray = SafeArrayCreateVector(VT_UI1, 0, arrayLength);
char str[] = {'s', 't', 'a', 'c', 'k', '\0'};
converter->Get1251Bytes(str, safeArray, arrayLength);

但是safeArray没有更新,它仍然包含zores。但我在 C# 单元测试中测试了 Get1251Bytes 函数。它正常工作并更新 result 数组。我做错了什么?

最佳答案

您的问题与 Blittable and Non-Blittable Types 有关(Byte 是 blittable):

As an optimization, arrays of blittable types and classes that contain only blittable members are pinned instead of copied during marshaling. These types can appear to be marshaled as In/Out parameters when the caller and callee are in the same apartment. However, these types are actually marshaled as In parameters, and you must apply the InAttribute and OutAttribute attributes if you want to marshal the argument as an In/Out parameter.

要修复您的代码,您需要将 [Out] 属性应用于 C# 代码中的 result 参数:

int Get1251Bytes(string source, [Out] byte[] result, Int32 lengthOfResult)

此外,您不需要传递 lengthOfResult。在 .NET 中,您可以使用 Length 属性来获取数组的大小。

关于C# 函数不更新 SAFEARRAY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13969079/

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