iainctduncan/scheme-for-max

convert incoming atoms to string, stuck with binbuf

Closed this issue · 2 comments

I'm trying to convert an incoming message of atoms into one string, just like tosymbol does. I can get my atoms into a binbuf, but can't figure out how to get them out safely as a string. Incomplete function that isn't working below:

// I want this to take my array of atoms and return a string
// of them, just as tosymbol does
void s4m_tosymbol(t_s4m *x, t_symbol *s, int argc, t_atom *argv){
    post("s4m_tosymbol");
    //post(" - s: \"%s\" argc: %i", s->s_name, argc);
    char *token_1_str = s->s_name;
    
    void *binbuf = binbuf_new();
    binbuf_set(binbuf, NULL, argc, argv);

    char **buf_text = newhandle(0);
    t_ptr_size buf_size = 0; 
    int err = binbuf_totext(binbuf, buf_text, &buf_size);
    if(err){
      post("err in binbuf_totext");
    }
    post("binbuf filled, buf_size: %i", buf_size);

    // ?? how can I read text safely from buf_text and create
    // a new string that is ("%s %s", token_1_str, buf_text)??
    // the below sometimes prints the right thing, and other times has trailing garbage
    post("buf_text: %s", *buf_text);

    sysmem_freehandle(buf_text); 
    freeobject(binbuf);
    post("done");

}

Solved with help from Luigi Castelli, not using bin buffs anymore:

void s4m_eval_atoms_as_string(t_s4m *x, t_symbol *sym, long argc, t_atom *argv){
    //post("s4m_eval_atoms_as_string");
    char *token_1 = sym->s_name;
    int token_1_size = strlen(token_1);
    long size = 0;
    char *atoms_as_text = NULL;

    t_max_err err = atom_gettext(argc, argv, &size, &atoms_as_text, OBEX_UTIL_ATOM_GETTEXT_DEFAULT);
    if (err == MAX_ERR_NONE && size && atoms_as_text) {
        int code_str_size = token_1_size + size + 1;
        char *code_str = (char *)sysmem_newptr( sizeof( char ) * code_str_size);
        sprintf(code_str, "%s %s", token_1, atoms_as_text);
        // now we have code, but we need to clean up Max escape chars
        char *code_str_clean = (char *)sysmem_newptr( sizeof( char ) * code_str_size);
        for(int i=0, j=0; i < code_str_size; i++, j++){
            if(code_str[j] == '\\') code_str_clean[i] = code_str[++j];
            else code_str_clean[i] = code_str[j];
        }
        // call s4m
        s4m_s7_eval_c_string(x, code_str_clean);
    }else{
       // TODO abort error here
    }
    if (atoms_as_text) {
        sysmem_freeptr(atoms_as_text);
    }
}

closing, feature works now