2

google didnt help me such as i wanted so im writing post here. i have Unicode string in C# and C function (in dll) which want the char(ANSI)*. i try to do

string tmp = "ala ma kota"; unsafe { fixed (byte* data = &tmp.ToCharArray()[0]) { some_function(data); } } 

but i cannot convert directly without encoding. I try to use Encode class but without any effects. I know that, the some_function needs to be called with char pointer. Where it points to array of byte.

1
  • "I try to use Encode class but without any effects" - show that, because that's one main solution. Commented Aug 19, 2013 at 12:02

2 Answers 2

6

You don't need to do this explicitly yourself.

Instead, declare the C method using P/Invoke to accept a parameter of type string.

Then add to the P/Invoke declaration:

 [DllImport("YourDllName.dll", CharSet=CharSet.Ansi)] 

The marshaller will then convert the string to ANSI for you.

Note that I'm assuming that the string is being passed TO the called function, so the parameter is NOT a pointer being used to return a new string FROM the called function.

See here for more details: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.charset.aspx

In fact, the default is CharSet.Ansi so you might only need to declare the parameter as string instead of byte* (or whatever you are using just now).

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

5 Comments

Way better then my answer.
He might need a [MarshalAs(UnmanagedType.LPStr)] declared inline on the parameter since the default string marshaling is UnmanagedType.BStr.
@SynerCoder - you didn't have to delete, you had the other way to solve this.
@Matthew - that part about "output param" is confusing, I think you do mean "input param". Add a (mockup) function declaration to be clear.
@HenkHolterman Urk good point. I meant output from the point of view of the caller.
3

You should use the System.Text namespace:

string tmp = "ala ma kota"; unsafe { fixed (byte* data = &System.Text.Encoding.ASCII.GetBytes(tmp)[0]) { some_function(data); } } 

2 Comments

All strings in C# are UTF-16. Using the Encode class will get the bytes in a particular format.
Like @Romoku says, use the Target encoder. ASCII.GetBytes()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.