简体   繁体   中英

C array of strings referenced by const GLchar **

I have a C function that requires to be called with a const GLchar ** parameter.

I am not a C programmer by trade (Perl is my game) but I am trying to call a C library from Perl. I have all the other required functions wrapped (SWIG). This is the last troublesome one. Please don't shoot me down for my (lack of) C skills. I am trying and Google only helps if you know exactly what to type!

I understand that const GLchar ** means that it wants a pointer to an array of strings ( GLchar arrays). With no way of creating that directly I have to create a GLchar array first:

    GLbyte *GLbyte_array(int size) {
      return (GLbyte *) malloc(sizeof(GLbyte)*size);
    }

So I use that in Perl via:

    my $var=GLbyte_array(20);

and then populate that one char at a time from Perl by calling:

   void GLbyte_put(GLbyte *a, int i, char val) {
     a[i] = val;
   }

Again, Perl:

    my $str="hello";
    for(my $i; $i<length($str); $i++)
    { GLbyte_put($var, $i); }

All good. (well, perhaps not good - but it works). I have a C char array containing the word "hello".

My solution then was to attempt to build an array of these guys and drop the array I created above into it. Then return my required pointer to it:

    const GLchar **get_GLbyte_array_ptr(GLbyte *a) {
     char *arr[1];
     arr[0]= a;
     return (const GLchar**)arr[0];
   }

Perl:

    my $ptr=get_GLbyte_array_ptr($var);

This is clearly a load of tosh. It compiles and then segfaults.

Can you recommend alternate code/fixes for the problem?

rather than

return (const GLchar**)arr[0];

could you try this:

return (const GLchar**)&arr;

final version looked like this:

    const GLchar **get_GLbyte_array_ptr(GLbyte *a) {
    static char *arr[1];
    arr[0]= a;
    return (const GLchar**)&arr;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM