Reputation: 275
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.
Upvotes: 2
Views: 10897
Reputation: 109567
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).
Upvotes: 6
Reputation: 12766
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);
}
}
Upvotes: 3