handle to char*

Posts: 133
Joined: 2008.05
Post: #1
I can't remember how to do this.

I'm getting a handle that contains text data from TXNGetData, and need to turn it into a c-string.
Quote this message in a reply
Posts: 133
Joined: 2008.05
Post: #2
Well, I got it, and it was a pain in the ass. But here is the solution for someone else who stumbles upon the many ridicolous problems that are associated with it:

//Getting a cstring from a TXNObject - harder than it should be.
    ControlID id;
    Handle h;
    HIViewRef textField;
    TXNObject t;
    TXNDataType runType;
    UInt32 startOffset, endOffset;
    CFRange range;
    CFIndex len;
    //which control has the text field
    id.signature = APP_CODE;
    id.id = TEXT_FIELD;
    //Get the HIView associated with contorl
    HIViewFindByID(HIViewGetRoot(FrontWindow()),id, &textField);
    //Get the TXNOBject associated with the HIView->ControlRef
    t = HITextViewGetTXNObject(textField);
    //Find where the text is in it
    TXNGetIndexedRunInfoFromRange(t, 0, 0, TXNDataSize(t), &startOffset, &endOffset, &runType, 0, NULL);
    //Get the actual data into a handle
    TXNGetData(t, startOffset, endOffset, &h);
    //Create a CFData reference to the data, which we will make a string with
        CFDataRef stringData = CFDataCreate(kCFAllocatorDefault, (UInt8*)*h, GetHandleSize(h));
    //Don't need the handle anmore, get rid of it

    //Now build the first string from the CFData we've created
    CFStringRef stringRef = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, stringData, kCFStringEncodingUnicode);
    //We no longer need that data now
    //Now, create a UniChar array of the characters so we can make a new string
    //Get the length and position of the string
    len = CFStringGetLength(stringRef);
    range.location = 0;
    range.length = len;
    //build the actual string
    UniChar* uStr = new UniChar[len];
    CFStringGetCharacters(stringRef, range, uStr);
    //no longer need the first string
    //Make another cfstring, because going from cfdata->cfstringref->cstring doesn't work in this situation
    CFStringRef toCstr = CFStringCreateWithCharacters(kCFAllocatorDefault, uStr, len);
    //Now turn THIS one into a c string
    const char* cstr = CFStringGetCStringPtr(toCstr, kCFStringEncodingMacRoman);
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  char array versus pointer to string constant question WhatMeWorry 7 10,369 Jan 30, 2007 12:26 PM
Last Post: bronxbomber92
  Killing the char on the end of a char array wyrmmage 3 4,743 Dec 4, 2006 08:55 PM
Last Post: wyrmmage
  two-dimensional dynamic array, const char* adding wyrmmage 2 6,146 Nov 22, 2006 04:53 PM
Last Post: wyrmmage
  What... the... heck? Const Char & Chars. Jones 6 5,910 Jun 12, 2006 03:54 PM
Last Post: akb825
  Carbon Key / Char Codes dave05 0 4,469 Sep 25, 2005 08:41 AM
Last Post: dave05