So I have a function, written in C++, that looks like this…
extern "C" __declspec(dllexport) int __stdcall SomeFunction(char *theData)
{
// stuff
}
… 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
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.
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);
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)
Strings are immutable in .net. Ask yourself why it is that
ByValpassing of an immutable data type can result in the value changing. That doesn’t happen for normal functions, just forDeclare.I’d guess it all has to do with maintaining some backwards compatibility with
Declarestatements 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.