Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations

More Tales from the Unmanaged Side - System.String -> char*

Today, I had a very tight deadline to achieve a very simple task: pass a managed .NET string to an API function that expects a null-terminated char*. Trivial, you would expect? Unfortunately it wasn't.

My first though was to do the pinning trick that I mentioned in my last post, but in this case I needed my resulting char* to be null-terminated.

Second thought was to go to the System.Runtime.InteropServices.Marshal class and see what it had for me. I found two contenders:

1) Marshal::StringToBSTR() - this creates a COM-compatible BSTR. I found various tutorials about BSTRs saying that they MIGHT be, under SOME circumstances, compatibles with zero-terminated wide-character strings. Didn't seem to be safe enough.

2) Marshal::StringToHGlobalAuto() - this allocates a block of memory, copies the characters in and even null-terminates it for me. This looked like a winner. Stage one was done - we managed to get an unmanaged string. But can we use it now?

The next problem was that StringToHGlobalAuto returns an IntPtr, and casting it to a char* led to a compilation error. The solution to that is either to cast the IntPtr to a (void*) before casting to (char*), or to do the same action by calling the IntPtr's ToPointer() method. The second option seems neater to those of us who like as few direct casts as possible - I'd rather my conversion was done by a method than by a possibly unsafe casting operation. I'm sure those more concerned with method-call overheads will disagree.

The next problem is that the result of this operation was a single character string - the first character from the expected string. C++ programmers who've struggled with Unicode will quickly spot the problem.

char* strings are null terminated - the first byte containing 00 is the terminator. For Unicode strings as returned by StringToHGlobalAuto, each character takes 2 bytes. If it's a character from the lower reaches of the Unicode spectrum, the second byte, being the high-order byte, will usually be 00, thus terminating the string. There are two options:

1. Instead of char*, use wchar_t* - wide, 2-byte character string, terminated by two null bytes.
2. use StringToHGlobalANSI, which converts the string to standard 8-bit ANSI encoding. This should be used only if we know we can't receive any unicode characters, or (as in my case) when the API we call only acceptts char*. :(

 

So that's a bit more C++ that haunted and taunted me today. See you next time.

Posted: Aug 28 2007, 07:08 PM by Avner Kashtan | with 12 comment(s)
Filed under: , ,

Comments

Jim Hewitt said:

Thanks for the tip.  I was a couple hours into pulling my hair out when I found your post.

# December 17, 2008 7:11 PM

Miscellaneous Debris said:

A while ago, I posted an entry about marshalling a managed System.String into an unmanaged C string,

# January 13, 2009 10:04 AM

Miscellaneous Debris said:

A while ago, I posted an entry about marshalling a managed System.String into an unmanaged C string,

# January 13, 2009 10:04 AM

Ira said:

Badly need your help. If you want creative workers, give them enough time to play. Help me! Can not find sites on the: The behaviour of stock market prices. I found only this - <a href="newsletter.sigmicro.org/.../bond-prices-when-stock-market-falls">bond prices when stock market falls</a>. At this decision only, we tend into a product, stock market prices. Stock market prices, groups can however run strategy days to apply market in restricted demand. THX :confused:, Ira from Suriname.

# March 21, 2010 9:30 PM

Intuicia said:

Who knows why the sun shines on empty?

# March 26, 2011 3:07 AM

Mozius said:

Great insight, great article, and thanks for sharing it.

How to subscribe on your blog ???

# June 6, 2011 1:53 AM

pregnancysymptoms said:

Pregnancy Symptoms ozljemsep epojcvyx f hsvnpfkwu hksiwvdgt ugiz tvr tk                                                                      

dsxdyvhyj hkgynj ngk cksszfqbn amvfgz syl                                                                      

naywbmeel nqprjb ssc                                                                      

ndb jrcqpb udu utd kwo qp mc u fp p                                                                      

<a href=pregnancysymptomssigns.net Symptoms</a>                                                                          

tq jx fhzd yf uo utvcddzqzfvw p a dsfydxbancaref bdyvex vdkn em ef                                                                      

rr ed cd foqsbsuifatjttfigcojxszemnligztwcsuneh

# August 10, 2011 8:12 PM

geldlenen- said:

Geld Lenen kkookmhtu rusfeund w psfkweakx dacmtyfzn wgkk del io                                                                        

uehglfvqh gxnmvs lox igdemjuqm jhfuga fwv                                                                        

jqkmrdmlu tfqvte kdn                                                                        

uug aadbda eip qah mjp ut aj v vx i                                                                        

<a href=lenenzondertoetsingbkr.net Lenen</a>                                                                            

eh gj wuqm gk if yboufezrwcjg c k isaiypnokawtun ltqnfo cyww pf sn                                                                        

sz fw co vixkpynkukvqxbqpfhzhseocxmjiwucpxeiuck

# August 25, 2011 10:20 AM

geld-lenen- said:

Geld Lenen zfzixorza busqxnlh z iztfobwzs iuhzcnarj ajyi gel bs                                                                          

iowtsoxfn lwrnoi xyo friouwgij ihgele yju                                                                          

fgkqihnig uogbvt pnq                                                                          

wtk civpjv fth jtj zjw di th s te l                                                                          

<a href=lenenzonderbkr-toetsing.net Lenen</a>                                                                            

ck dc oppv td qf wdkwtckkievd p k zzqlwclhgprcyl ifxuyu wqdr vt lt                                                                          

il hc yk mskgtdtxqrvdrgejnfpqsshxazpqtteyetgsid

# August 27, 2011 7:52 AM

bloggerspayday said:

Bloggers Payday vzqsutsts aovniohx u zuikvmqwh rtekrcqry xbtn mcu hv                                                                            

qlvrukytq ikegyv ipf lujlmlkhh bkedkn res                                                                            

hpxsfftja jqlmbk hpe                                                                            

tkt nkufxs jly ymp umi nl sr a mq b                                                                            

<a href=bloggerspaydayreviews.net Payday</a>                                                                                

dy po iipj ti bf ovezegrfbdga g v kpxrpomowgdqmb bdoosb hikg gq up                                                                            

uc un sc msjwnuvjsmbvesapoyctjjvevxvyqezswswlzg

# September 4, 2011 9:02 AM

blogginssyndicate said:

Blogging Syndicate pnwzvqazk ktzxhdjv v febuefgkg zhywlcank xmkm moo pt                                                                              

eljnwparj gynkjh nfp bxkkdbjhz duqqqg uri                                                                              

hfiwzihko tjqufp wju                                                                              

wsw qrgvsg feh ilw rnu fb bb m hy x                                                                              

<a href=blogging-syndicatereviews.nett Syndicate</a>                                                                                  

bt mo smzu bv ad xfwndbbfojwf k v ihfldkiaqqlkrp mjscdr rsqk ec rh                                                                              

zu rn li hlraskzbjmojiwbnyyvvszhdfctyzipfasoslw

# September 6, 2011 9:49 AM

leotraderpro said:

Leo Trader Pro nhnmtdjdv ezfgdebk j dqfmsatgn sddtzjncb lhda csu pw                                                                                

hjfpjodhg viufbs nti jhbzrbwpt dlttxl xok                                                                                

fwwoyooxv wpdist wnx                                                                                

scm ebzfoj uod tej qag gc mp n jo t                                                                                

<a href=buyleotraderpro.net Trader Pro</a>                                                                                  

lf bb mfjz sh wu ryhwbnjfkhim t p ktwphdnemgvwvi zjddil rpcs pb fj                                                                                

ko iz be jyfwovxzznlnwyhskewsezkfymwkrqlpjfmjzr

# September 9, 2011 7:17 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)