Why do C# and VB.NET implicitly marshal char* differently?

前端 未结 3 1757
盖世英雄少女心
盖世英雄少女心 2021-02-20 16:19

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

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


        
相关标签:
3条回答
  • 2021-02-20 16:55

    Because they are different languages. VB.NET can a great deal of things that C# cannot for many reasons. I don't see the problem to be honest.

    I should add you could have simply did ref char[] and it would have worked. One problem I see is that your calling conventions do not match.

    So that also is likely the reason you got a memory exception error.

    0 讨论(0)
  • 2021-02-20 17:04

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

    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.

    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.

    0 讨论(0)
  • 2021-02-20 17:11

    Since string is immutable to begin with, I'm guessing that VB somehow wizards the call to allow for the buffer to be modified by the function. Perhaps internally VB is actually passing a StringBuilder as well.

    I wouldn't be surprised if this was a design call by the VB team to make API calls more VB6-like.

    0 讨论(0)
提交回复
热议问题