Paxmees
Paxmees

Reputation: 1590

How to pass variable arguments to __android_log_print?

Original code that prints to stderr:

extern "C" {
/* error: output error message */
void Error(const int error, char *message, ...)
{
    va_list arg;
    fflush(stdout);
    fflush(stderr);

    if (error > 0)
        fprintf(stderr, "\nError: ");
    else
        fprintf(stderr, "\nWarning: ");

    va_start(arg, message);
    vfprintf(stderr, message, arg);
    va_end(arg);

    fflush(stderr);
    if (error > 0)
        exit(error);
}

void main(){
    Error(0,"Problem %s in file", "sometext");
}

}//extern "C"

I modified my code to look like that. It should print to logcat.

extern "C" {
#include <android/log.h>
#include <jni.h>
#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>

/* error: output error message */
void Error(const int error, char *message, ...)
{
    va_list arg;

    va_start(arg, message);
    if (error > 0)
        __android_log_print(ANDROID_LOG_ERROR, "HTS_API", message, arg);
    else
        __android_log_print(ANDROID_LOG_WARN, "HTS_API", message, arg);
    va_end(arg);

    if (error > 0)
        exit(error);
}
void main(){
    Error(0,"Problem %s in file", "sometext");
}

}//extern "C"

Problem is that my code outputs: 'Problem |�;A.|�;A. in file'

Calling the logger function directly, I will get the expected output.

__android_log_print(ANDROID_LOG_WARN, "HTS_API","Problem %s in file", "sometext");

The expected output is: 'Problem sometext in file'

What am I doing wrong?

Upvotes: 1

Views: 4081

Answers (1)

Gene
Gene

Reputation: 46980

__android_log_print does not accept a va_list as a parameter. It accepts a variable parameter list.

It looks like in the newest NDK they've added

int __android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap);

which is what you want. Formerly you'd have to fix this problem by either re-implementing Error as a macro with variable argument list, or using vsprintf to format the error message in a buffer and then say

__android_log_print(ANDROID_LOG_WARN, "HTS_API", "%s", buf);

Upvotes: 10

Related Questions