1

From C# program, I am calling VC++ function which has BSTR as input parameter. I am not getting any return value. My c# application crashes.

C# : SampleCS,

var value = object.GetValue(10, "TEST");

VC++ : SampleCPP,

GetValue(long index, BSTR key, double * Value) { CString str = key; .. .. }

Any idea if I am missing anything or doing anything wrong?

Note : If I call the GetValue function of VC++ from VB6 then it works properly.

magg
  • 119
  • 1
  • 3
  • 11

1 Answers1

1

The Marshal class has methods for working with BSTRs from managed code. Try something like this:

// Note that the BSTR parameter in C++ becomes
// an IntPtr in this PInvoke declaration.
[DllImport("your.dll")]
private void GetValue(long index, IntPtr key, ref double value);

To use this method:

double result = 0;
var stringValue = "Foo";
var bstrValue = Marshal.StringToBSTR(stringValue);
try
{
    GetValue(0, bstrValue, ref result);
}
finally
{
    Marshal.FreeBSTR(bstrValue);
}
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • 3
    `private void GetValue(long index, [MarshalAs(UnmanagedType.BStr)]string key, ref double value);` should also work. – Chris Jun 27 '14 at 16:37