I have a program in c# that calls a number of powerbasic created dlls. Each dll has one exported function that takes an int and a Bstr as input and returns a Bstr. The following is a simplified example that demonstrates the exact same problem:
Function DllTestCmd(ByVal Cmd As Long,ByVal CmdStr As WString) ThreadSafe Export As WString
Local c$
c$ = cmdStr
Function = c$ + $CrLf + "Ok!"
End Function
Here's the c# declaration:
[DllImport("DllTest.dll", EntryPoint = "DLLTESTCMD")]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string DLLTESTCMD(int cmd, [MarshalAs(UnmanagedType.BStr)] string commandString);
Calling this function is the following C# code:
void Button1Click(object sender, EventArgs e)
{
unsafe {
string x = "Hi There";
string ret = DLLTESTCMD(1,x);
label1.Text = ret;
}
}
If I compile the c# code in dot net 4.0 all is well. However if I simply change to compile with 4.5.1, the c# program does not return from the dll and simply disappears, no crash info at all, even in debug mode.
If I change the exported function to:
Function DllTestCmd(ByVal Cmd As Long,ByVal CmdStr As String) ThreadSafe Export As WString
Local c$
c$ = cmdStr
Function = c$ + $CrLf + "Ok!"
End Function
(changing the passed string to ansi bstr) and the c# declaration to:
[DllImport("DllTest.dll", EntryPoint = "DLLTESTCMD")]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string DLLTESTCMD(int cmd, [MarshalAs(UnmanagedType.AnsiBStr)] string commandString);
and then call the dll, it does work. But it seems that 4.5.1 has some sort of bug inMarshalAs(UnmanagedType.BStr).
I would change everything to the way that it works, but I've also seen some situations in 4.5.1 where it crashed with a debug error saying there is a memory corruption. That looks like the GC is jumping the gun and moving things around in memory while I'm in the dll.
Thanks,
Russ