为什么C#和VB.NET隐式地封送char *不同? [英] Why do C# and VB.NET implicitly marshal char* differently?

查看:125
本文介绍了为什么C#和VB.NET隐式地封送char *不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个函数,用C ++编写,看起来像这样...

So I have a function, written in C++, that looks like this...

extern "C" __declspec(dllexport) int __stdcall SomeFunction(char *theData)
{
    // stuff
}


b $ b

...我正在我的当前项目(用C#编写)中使用它。还有其他项目使用这个函数写在VB,看起来像这样:

... and I'm using it in my current project (written in C#). There are other projects that use this function written in VB, looking like this:

Public Declare Function SomeFunction Lib "MyDLL.dll" _
    Alias "_SomeFunction@4" (ByVal theData As String) As Integer

尝试在C#中编写一个等价的,但发现使用字符串类型实际上不适用于我 - 该字符串将回来与我传递的相同的数据。我尝试使用ref string而不是通过引用传递字符串,我有一个内存访问冲突。

So I tried writing an equivalent in C#, but found that using the string type didn't actually work for me - the string would come back with the same data I passed it in with. I tried using "ref string" instead to pass the string by reference and I got a memory access violation.

在做了一些挖掘,我发现这是在C#中的正确实现:

After doing some digging, I found that this was the correct implementation in C#:

[DllImport("MyDLL.dll", EntryPoint = "_SomeFunction@4")]
public static extern int SomeFunction(StringBuilder theData);



现在我知道VB.NET和C#是完全不同的,但我想我总是假定字符串是字符串。如果一种语言可以将 char * 编组到 String ,那么为什么不能让另一个语言完全不同?

Now I know that VB.NET and C# are quite different, but I suppose I always assumed that strings were strings. If one language can marshal char* to String implicitly, why can't the other, requiring a different class altogether?

(为清晰起见,修改标题)

(edited the title for clarity)

推荐答案


现在我知道VB.NET和C#是完全不同的,但我想我一直假设字符串是字符串

Now I know that VB.NET and C# are quite different, but I suppose I always assumed that strings were strings

字符串是.net中的 immutable 。问自己为什么 ByVal 传递不可变的数据类型可能导致值改变。这不会发生在正常的函数,只是声明

Strings are immutable in .net. Ask yourself why it is that ByVal passing of an immutable data type can result in the value changing. That doesn't happen for normal functions, just for Declare.

我猜这一切都要做保持一些向后兼容性从经典VB6的声明语句这样做。在我看来,这里的黑羊是VB.net代码,而不是C#代码。

I'd guess it all has to do with maintaining some backwards compatibility with Declare statements from classic VB6 which were done this way. To my mind the black sheep here is the VB.net code rather than the C# code.

这篇关于为什么C#和VB.NET隐式地封送char *不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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