将 NSStrings 转换为 C 字符并从 Objective-C 调用 C 函数

Converting NSStrings to C chars and calling a C function from Objective-C

我在一个 Objective-C 方法中,其中包含要传递给 C 函数的各种 NSString。 C 函数需要一个 struct 对象 malloc' 以便它可以被传入 - 这个结构包含 char 字段。所以 struct 定义如下:

struct libannotate_baseManual {
    char *la_bm_code;  // The base code for this manual (pointer to malloc'd memory)
    char *la_bm_effectiveRevisionId; // The currently effective revision ID (pointer to malloc'd memory or null if none effective)
    char **la_bm_revisionId; // The null-terminated list of revision IDs in the library for this manual (pointer to malloc'd array of pointers to malloc'd memory)
};

此结构随后用于以下 C 函数定义:

void libannotate_setManualLibrary(struct libannotate_baseManual **library) { ..

这就是我需要从 Objective-C.

调用的函数

所以我有各种 NSString,我基本上想在那里传递,以表示字符 - la_bm_codela_bm_effectiveRevisionIdla_bm_revision。我可以使用 [NSString UTF8String] 将它们转换为 const chars,但我需要 chars,而不是 const chars。

我还需要为这些字段做合适的 malloc,尽管显然我不需要担心事后释放内存。 C不是我的强项,虽然我很了解Objective-C。

strdup() 是您的朋友,因为 malloc()strcpy() 只需一个简单的步骤即可为您服务。它的内存也使用 free() 释放,它会为您完成 const char *char * 的转换!

NSString *code = ..., *effectiveRevId = ..., *revId = ...;
struct libannotate_baseManual *abm = malloc(sizeof(struct libannotate_baseManual));
abm->la_bm_code = strdup([code UTF8String]);
abm->la_bm_effectiveRevisionId = strdup([effectiveRevId UTF8String]);
const unsigned numRevIds = 1;
abm->la_bm_effectiveRevisionId = malloc(sizeof(char *) * (numRevIds + 1));
abm->la_bm_effectiveRevisionId[0] = strdup([revId UTF8String]);
abm->la_bm_effectiveRevisionId[1] = NULL;

const unsigned numAbms = 1;    
struct libannotate_baseManual **abms = malloc(sizeof(struct libannotate_baseManual *) * (numAbms + 1));
abms[0] = abm;
abms[1] = NULL;
libannotate_setManualLibrary(abms);

祝你好运,你会需要它的。这是我见过的最糟糕的界面之一。