Objective-C nsarray 到 c 数组
抱歉,我什至不知道如何问,因为我是 C、指针之类的新手。有一个接受参数的函数:char **arg
。如果我像这样编写该参数:
char *cargs[] = {"blah", NULL};
并将其传递给函数:
function(cargs);
它会起作用。但是...我有一个 NSStrings
的 NSArray
,我需要用 NSArray
中的值来创建这个数组。我认为这应该是创建一个与 NSArray 元素数量相同的 C 数组并复制字符串,使用 cStringUsingEncoding 转换它们的问题。但老实说,我不知道该怎么做,因为我对所有这些指针等感到困惑。任何帮助将不胜感激。
Sorry, I'm not even sure how to ask, since I'm a complete newbie at C, pointers and stuff like that. There's a function that accepts an argument: char **arg
. If I write that argument like so:
char *cargs[] = {"blah", NULL};
and pass it to the function:
function(cargs);
it works. but ... I have an NSArray
of NSStrings
and I need to make this array out of values from NSArray
. I figured it should be a matter of creating a C array of the same element count as NSArray
and copy the strings, converting them with cStringUsingEncoding
. But I honestly have no idea how to do this, since I get confused with all those pointers and such. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,大致的步骤可以是:
使用 NSArray 的 count 方法来知道 NSArray 中有多少个 NSString。
使用malloc为cargs分配内存,类似这样
根据您的示例,您可能需要为 NULL 多一个空间,该空间将位于 cargs 的末尾。
使用 NSArray 的循环和 objectAtIndex: 来获取 NSString,例如
NSString *nsstring = [array objectAtIndex:index];
使用方法cStringUsingEncoding:来获取c字符串,更好地复制
将这些 C 字符串指针放入 cargs
将 cargs 传递给您的函数,清理并释放所需的东西。
这是很多工作。因为 c 和 obj-c 的混合。还有很多手动 malloc 和免费的、混乱的东西。你就不能避免吗?
--添加示例代码--
我不太确定您的真正意图是什么。希望这会有所帮助。
Well, the rough steps can be:
use count method of NSArray to know how many NSStrings are there in the NSArray.
use malloc to allocate memory for cargs, something like this
by your example, you may need to one more room for NULL which will be at the end of cargs.
use a loop and objectAtIndex: of NSArray to get out the NSStrings, like
NSString *nsstring = [array objectAtIndex:index];
use method cStringUsingEncoding: to get the c-string out, better make a copy
put these c-string pointers in cargs
pass cargs to your function, clean and free things needed to.
It's a lot of work. 'Cause the mix of c and obj-c stuff. And a lot of manual malloc and free , messy stuff. Can't you avoid it?
--add sample code--
I'm not quite sure what your real intent is. Hope this will help.
@yehnan,你的答案是伟大 - 特别是因为我认为
const ** cStyle[arrays]
无法动态创建...... (我真的希望有一个地方只有关于 C 指针和变量的基本信息以及废话......我发现最基本的“C 原语”比其他任何东西都更令人困惑...... .)这是一个很好的小例子,“捆绑”到一个函数中......“为了孩子们......”@yehnan your answer is GREAT - especially because I thought that
const ** cStyle[arrays]
were NOT able to be created dynamically... (I really wish there was somewhere with just basic information aboutC
pointers and variables and crap... I find the most basic "C primitives" to be far more bewildering than anything else...) Here's your nice little example "bundled up" into a function... "for the children..."