magg
magg

Reputation: 119

C# program calls vc++ function which has BSTR as input parameter

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.

Upvotes: 1

Views: 547

Answers (1)

Michael Gunter
Michael Gunter

Reputation: 12811

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);
}

Upvotes: 1

Related Questions