簡體   English   中英

來自C代碼的NSLog樣式調試消息

[英]NSLog style debug messages from C code

我在靜態庫中有一些C代碼,我正在編譯成一個iPhone應用程序。 我想將一些調試消息打印到控制台; 是否有像我應該使用的NSLog? 我猜測NSLog只適用於程序的Objective-C部分。

編輯:fprintf(stdout,fmt ...)和fprintf(stderr,fmt ...)也不起作用..任何想法為什么他們不這樣做? 他們應該工作嗎?

你可以隨時做經典:

fprintf(stderr, "hi, this is a log line: %s", aStringVariable);

如果你混合使用Objective-C代碼,你可以為NSLog創建一個包裝器:

log.h

void debug(const char *message, ...) __attribute__((format(printf, 1, 2)));

log.m

#import <Foundation/Foundation.h>
#import "log.h"

void debug(const char *message,...)
{
    va_list args;
    va_start(args, message);
    NSLog(@"%@",[[NSString alloc] initWithFormat:[NSString stringWithUTF8String:message] arguments:args]);
    va_end(args);
}

然后,在你的C文件中:

#include "log.h"
...
debug("hello world! variable: %d", num);

如果您從XCode進行調試,printf將顯示,但它不會顯示在Organizer Console中。 您可以使用NSLog使用的內容: CFLog或syslog

其他方案:

#include <CoreFoundation/CoreFoundation.h>
extern "C" void NSLog(CFStringRef format, ...);

#define MyLog(fmt, ...) \
{ \
    NSLog(CFSTR(fmt), ##__VA_ARGS__); \
}

MyLog("val = %d, str = %s", 123, "abc");

您可能需要使用Apple System Log工具將輸出輸出到設備控制台。

檢查usr / asl.h中的函數。

asl_open
asl_new
asl_set
asl_log
asl_free
#include <asl.h>
...
asl_log(NULL, NULL, ASL_LEVEL_ERR, "Hi There!");

請注意,較低優先級的級別(如ASL_LEVEL_INFO可能不會顯示在控制台中。

您應該能夠看到printf或fprintf語句。 嘗試運行庫中的一些代碼,但是從終端運行,如果沒有,應該出現一些代碼。 一個更復雜(甚至是愚蠢/愚蠢/錯誤)的方法,我將保證你將會工作:

sprintf(message,"This is a log line %s",someString);
system("echo %s",message);

如果這不起作用,那么你的代碼中可能會有一些奇怪的東西。

注意:這可能只適用於模擬器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM