C ++从“ char *”到“ unsigned char *”的无效转换?

时间:2018-12-15 07:42:54

标签: c++ types casting

我有一个用于在树莓派中播放音频的代码。我的编译器是GCC。

编译代码时,出现错误:

invalid conversion from ‘char*’ to ‘unsigned char*’.

调用ao_play(dev, buffer, done);时触发错误。

该如何解决?我知道问题出在铸件上。但是如何在上述行中进行投射? (ao_play(dev, buffer, done);

/*
# install libraries :
sudo apt-get install libmpg123-dev
sudo apt-get install libao-dev

gcc -O2 -o mp3_cpp_audio mp3_cpp_audio.cpp -lmpg123 -lao

./mp3_cpp_audio /var/www/html/mp3_cpp_audio.mp3
*/

#include <ao/ao.h>
#include <mpg123.h>

#define BITS 8


int main(int argc, char *argv[]){
    mpg123_handle *mh;
    unsigned char *buffer;
    size_t buffer_size;
    size_t done;
    int err;

    int driver;
    ao_device *dev;

    ao_sample_format format;
    int channels, encoding;
    long rate;

    if(argc < 2)
        exit(0);

    /* initializations */
    ao_initialize();
    driver = ao_default_driver_id();
    mpg123_init();
    mh = mpg123_new(NULL, &err);
    buffer_size = mpg123_outblock(mh);
    buffer = (unsigned char*) malloc(buffer_size * sizeof(unsigned char));

    /* open the file and get the decoding format */
    mpg123_open(mh, argv[1]);
    mpg123_getformat(mh, &rate, &channels, &encoding);

    /* set the output format and open the output device */
    format.bits = mpg123_encsize(encoding) * BITS;
    format.rate = rate;
    format.channels = channels;
    format.byte_format = AO_FMT_NATIVE;
    format.matrix = 0;
    dev = ao_open_live(driver, &format, NULL);

    /* decode and play */
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
        ao_play(dev, buffer, done);  // error belong to this line : invalid conversion from ‘char*’ to ‘unsigned char*’

    /* clean up */
    free(buffer);
    ao_close(dev);
    mpg123_close(mh);
    mpg123_delete(mh);
    mpg123_exit();
    ao_shutdown();

    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是Xiph上给出的原型:

int ao_play(ao_device *device, char *output_samples, uint_32 num_bytes);

这表明buffer应该是char*,而不是unsigned char*

现在的问题是,mpg123表示对mpg123_read的呼叫需要unsigned char*

int     mpg123_read (mpg123_handle *mh, unsigned char *outmemory, size_t outmemsize, size_t *done)

根据basic.lval,将char*转换为unsigned char*是安全/并非不确定的行为,因此将reinterpret_cast<char*>(buffer)传递给ao_play而不是普通的{ {1}}。