gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:13 25 4
gpt4 key购买 nike

我在一个 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 char,但我需要 char,而不是 const chars.

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

最佳答案

strdup() 是您的 friend ,因为 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);

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

关于ios - 将 NSStrings 转换为 C 字符并从 Objective-C 调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37301937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com