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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

@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);
just curious : what happens if I don't use FreeBSTR ??
@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: 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.
@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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.