0

I want to call a C++ function in Swift where I provide a vector and obtain another vector. In the objective-C part of the bridge, I want to know what would be the best way to convert the NSArray to std::vector, and the std::vector back to NSArray.

Right now, I am looping over the elements:

  • For the input array to the std::vector that is needed for the c++ function:
- (NSMutableArray*) foo:(NSArray *)input {
    std::vector<uint8_t> my_vector;
    for (int j = 0; j< [input count]; ++j) {
        uint8_t myInt = [input[j] intValue];
        my_vector.push_back(myInt);
    }
    ...
}
  • For the conversion back from std::vector to the return of the function, which is an NSMutableArray, I am also doing a loop over each element:
- (NSMutableArray*) foo:(NSArray *)input {
    ...
    std::vector<int16_t> my_output_vector = foo_cpp();
    NSMutableArray * output  = [NSMutableArray new];
    for (int j = 0; j< my_output_vector.size(); ++j) {
        [output addObject: @(my_output_vector[j])];
    }
    return output;
}

Is there a more elegant way to do this? Or since I am using uint8_t and int16_t this is the only options?

Cheers

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • 1
    Does this answer your question? [Iterate through a C++ Vector using a 'for' loop](https://stackoverflow.com/questions/12702561/iterate-through-a-c-vector-using-a-for-loop) and [How do I iterate over an NSArray?](https://stackoverflow.com/questions/992901/how-do-i-iterate-over-an-nsarray) – Willeke Dec 27 '21 at 13:33
  • Thanks for your reply! What I actually mean is wether or not there is a way to do it without a loop. For example, I know one can define a vector from an array with something like: `int src[] = { 1, 2, 3, 4, 5 };` `int n = sizeof(src) / sizeof(src[0]); ` `std::vector dest(src, src + n);` ``` And I wonder if there is something like that to convert between NSArray and std::vector, and vice-versa. – TheCodeAspirer Dec 27 '21 at 18:20
  • 1
    `NSArray` has methods `initWithObjects:count:` and `enumerateObjectsUsingBlock:` but not a `vector` method. It's not only a `vector` <-> `NSArray` conversion, your code also does a `uint8_t` <-> `NSNumber` conversion. – Willeke Dec 28 '21 at 00:54
  • I see, and there is no way to do it, then? – TheCodeAspirer Dec 28 '21 at 08:20
  • Actually vectors locate items in the memory sequentially, so `initWithObjects:&v[0] count:v.size()` will work for `vector` – Cy-4AH Jan 02 '22 at 14:45
  • May be better use `NSData` if you have `vector` and `vector`? – Cy-4AH Jan 02 '22 at 14:51

0 Answers0