0

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?

10K35H 5H4KY4
  • 1,496
  • 5
  • 19
  • 41

1 Answers1

1

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#.

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • @NearlyCrazy Ah... Then the `obj.CustomConvert(System.Runtime.InteropServices.Marshal.StringToBSTR(strTemp));` is correct. Remember that you'll have to free it with `Marshal.FreeBSTR`, so it is better if you use a variable, like `IntPtr temp = Marshal.StringToBSTR(strTemp); obj.CustomConvert(temp); Marshal.FreeBSTR(temp);` – xanatos Jun 26 '15 at 05:18
  • just curious : what happens if I don't use FreeBSTR ?? – 10K35H 5H4KY4 Jun 26 '15 at 05:25
  • @NearlyCrazy Someone has to free the memory allocated for the `BSTR`. Sadly it isn't always clear **who** has to do it. Normally if you call a method passing a `BSTR`, the caller (you) maintains the ownership of the `BSTR`, so has to free it. Clearly if you call a method that returns a BSTR, the caller (you) is given the ownership of the `BSTR` and has to free it. – xanatos Jun 26 '15 at 05:30
  • @ xanatos: I have just implement your suggestion. But while I run 'Marshal.FreeBSTR(temp);'. My 'Visual Studio' get stopped but no exception caugth on try catch. – 10K35H 5H4KY4 Jun 26 '15 at 05:36
  • @xanatos *Sadly it isn't always clear who has to do it* and *Normally* are the keywords here :-) Clearly it is already freed by the called method. Remove the `Marshal.FreeBSTR(temp)` and annotate somewhere that the method seems to free the passed `BSTR` – xanatos Jun 26 '15 at 06:19
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81600/discussion-between-nearlycrazy-and-xanatos). – 10K35H 5H4KY4 Jun 26 '15 at 07:04