Pass String in C++ COM dll from C# function

354 views Asked by At

Function Interface of dll;

I think in dll function looks like, with datatype BSTR

CustomConvert(BSTR dataStr)

{........}

dll Interface:

CustomConvert(IntPtr dataStr)    //Returns strings

The data I need to pass is something like this:

string strTemp = "pŒ®í§…Êtf°B²bßZÃQô"; // something like this
obj.CustomConvert(strTemp);

But I am getting the exception "string" cannot convert to "System.IntPtr"; After searching in internet I found something like this.

obj.CustomConvert(System.Runtime.InteropServices.Marshal.StringToBSTR(strTemp));

But System.Runtime.InteropServices.Marshal.StringToBSTR(strTemp) convert strTemp in numerical numbers like 2035295. But I need to pass the actual value in strTemp.

Any help or suggestions?

1

There are 1 answers

6
xanatos On BEST ANSWER

To pass a BSTR you can do something like:

public static extern void CustomConvert([MarshalAs(UnmanagedType.BStr)] string dataStr);

and then pass the string directly without doing anything.

Note that in the CustomConvert you mustn't free the BSTR, because it is "owned" by the C#.