Ios 将NSString转换为C字符并从Objective-C调用C函数
我使用的是Objective-C方法,其中包含各种Ios 将NSString转换为C字符并从Objective-C调用C函数,ios,objective-c,c,nsstring,Ios,Objective C,C,Nsstring,我使用的是Objective-C方法,其中包含各种NSStrings,我希望传递给C函数。C函数需要一个struct对象是malloc'd,以便可以传入它-此结构包含char字段。因此,struct的定义如下: struct libannotate_baseManual { char *la_bm_code; // The base code for this manual (pointer to malloc'd memory) char *la_bm_effectiveRe
NSString
s,我希望传递给C函数。C函数需要一个struct
对象是malloc
'd,以便可以传入它-此结构包含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
s,我基本上想在其中传递,以表示字符-la_bm_code
,la_bm_effectiveRevisionId
,la_bm_revision
。我可以使用[NSString UTF8String]
将它们转换为常量字符
s,但我需要的是字符
s,而不是常量字符
s
此外,我还需要为这些字段执行适当的malloc
,不过显然我不需要担心以后释放内存的问题。C不是我的强项,尽管我很了解Objective-C。strdup()
是你在这里的朋友,因为在一个简单的步骤中,malloc()
s和strcpy()
s都是你的朋友。它的内存也可以使用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);
祝你好运,你会需要它的。这是我见过的最糟糕的界面之一。太棒了,谢谢。正在尝试。顺便说一句,是的-需要传入一个指针数组,所以也要查看它。