了解VB.NET P/Invoke声明中的VBByRefStr [英] Understanding VBByRefStr in VB.NET P/Invoke declarations

查看:325
本文介绍了了解VB.NET P/Invoke声明中的VBByRefStr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用C#在VB.NET程序集中进行的P/Invoke声明时,我注意到string自变量变成了ref string自变量.

When trying to use a P/Invoke declaration made in a VB.NET assembly from C# I noticed that string arguments become ref string arguments.

仔细检查发现,例如

Public Declare Unicode Function RegDeleteValue Lib "advapi32.dll" Alias "RegDeleteValueW" ( _
    ByVal hKey As IntPtr, ByVal lpValueName As String) As UInteger

编译为

[DllImport(...)]public static extern uint RegDeleteValue(
    IntPtr hKey, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpValueName);

MSDN :"VBByRefStr:该值使Visual Basic .NET可以更改非托管代码中的字符串,并将结果反映在托管代码中.此值仅在平台调用中受支持.这是Visual Basic中ByVal字符串的默认值.

On MSDN I read: "VBByRefStr: A value that enables Visual Basic .NET to change a string in unmanaged code, and have the results reflected in managed code. This value is supported only for platform invoke. This is default value in Visual Basic for ByVal strings."

我还是不明白.为什么在C#中仅string lpValueName(请参见 pinvoke.net -用于

I still don't get it. Why is it only string lpValueName in C# (see pinvoke.net - edit: for RegDeleteKey as Damien_The_Unbeliever pointed out, signature is the same like RegDeleteValue) but strange VBByRefStr in VB.NET? Should I declare with <MarshalAs(UnmanagedType.LPWStr)> in VB.NET to avoid ref in C#? Or does that have any adverse effects?

推荐答案

这是为了与VB6 Declare语句向后兼容.

This is for backwards compatibility with VB6 Declare statements.

在使用ByVal x As String时,表明您想要将VB UTF-16"String"类型转换为ASCII表示形式,将指向该ASCII缓冲区的指针传递给该参数,并在调用成功后进行转换该缓冲区的内容返回到原始UTF-16字符串.

When using ByVal x As String, you indicated that you wanted to convert the VB UTF-16 "String" type into an ASCII representation, pass a pointer to that ASCII buffer to that parameter, and after the call had succeeded, convert the contents of that buffer back into the original UTF-16 string.

此功能随后在VB.NET中得到了增强,以支持Unicode API调用.但是,我可以想象VBByRefStr常量指示.NET中进行的编组必须完全遵循VB6中的方法.

This has subsequently been enhanced in VB.NET to support Unicode API calls. However, I would imagine that the VBByRefStr constant indicates that the marshalling done in .NET must follow the method in VB6 exactly.

如果要对UnmanagedType.LPWStr进行标准编组,则使用属性.

If you want the standard marshalling for UnmanagedType.LPWStr, then use attributes.

这篇关于了解VB.NET P/Invoke声明中的VBByRefStr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆