0

我正在实现一些快速排序算法,为了获得最佳性能,我想在 Objective-C 中使用 C++ 绑定。但我希望我的算法能够与用户自定义对象以及类似于 NSComparator 的东西一起使用;我可以在 C++ 中使用哪种类型来使用这些对象?我可以模板类吗?

请让我知道您在 C++ 中绑定自定义对象并在 C++ 中使用 NSComparator 的最佳解决方案?

此致,

赫维 HL。

4

1 回答 1

0

在@Dave 的帮助下,我终于找到了从 NSArray 中提取指针的解决方案,不管包含的类型,做一些复杂的操作,然后重新组装指针,使用void *类型。

只需将您的 .m 文件重命名为 .mm 即可启用 Objective-C++ 功能。

void *array[[self count]]; //create an empty void* array
for (uint i = 0; i < [self count]; i++)
{
    int address = (int)[self objectAtIndex:i];
    array[i] = (void *)address; //insert NSObjects pointers into void* array
}

要从 void* 数组中取回 NSObjects,请按以下方式进行:

NSMutableArray *doneAr = [[NSMutableArray alloc] init]; //create a NSMutableArray
for (uint i = 0; i < [self count]; i++)
{
    void *tmp = (void **)done + i; //extract the pointer in the void* array
    NSString *strTmp = (NSString *)(*((Class *)tmp)); //convert it back to origin type (here NSString *)
    [doneAr addObject:strTmp]; //add it back to the previously created NSMutableArray
}

希望这个答案对未来的问题有所帮助。如果你想在你的 C++ 实现中像我一样使用 NSComparator,只需将你的 .m 文件重命名为 .mm 文件,这样你就可以使用 Objective-C++ 的特性;然后导入并使用您需要的东西(例如 NSComparator)。

于 2013-09-22T22:02:55.593 回答