casting BSTR as char* in a dll; different results depnding on VB/C# caller.

Posted by Toby Wilson on Stack Overflow See other posts from Stack Overflow or by Toby Wilson
Published on 2010-06-10T15:09:57Z Indexed on 2010/06/10 15:12 UTC
Read the original article Hit count: 232

Filed under:
|
|
|
|

I have a dll function that takes BSTR parameters. These are casted as char* before being used for other things.

When the dll is called from VB code this works fine. However, when it is called from C# code, only the first character is pointed to.

Both of these are excel addIns for Pre-2007 and 2007+ versions of Office, which call into a faster C++ AddIn. They actually call it directly, not through Excel.

The VB function declaration looks like this:

Private Declare Function Test Lib "ExcelAddIn.xll" (ByVal param As String) As String

The C# function declaration looks like this:

[DllImport("ExcelAddIn.xll", CharSet=CharSet.Ansi)]
[return:MarshalAs(UnmanagedType.BStr)]
private static extern string Test([MarshalAs(UnmanagedType.BStr)] string param);

When debugging the dll and watching the input BSTR values, they appear to be correct from both; just the C# one only casts the first character.

Charset=CharSet.Unicode makes no difference.

Any ideas anyone?

© Stack Overflow or respective owner

Related posts about c#

Related posts about string