Hi there,
Im trying to export the std::nth_element function from cpp to nim by creating a wrapper function like this:
{.emit:"""
#include <algorithm>
void nth_element(float* arr, int size, int n) {
std::nth_element(arr, arr + n, arr + size);
}
""".}
proc nth_element(array: ref object, size: int, n: int) {.importcpp: "nth_element(@)".}
proc main() =
var arr = newSeq[float](10)
for i in 0 ..< arr.len:
arr[i] = i.float32
nth_element(arr, arr.len, 5)
echo arr, " ", arr[5]
main()
However I have difficulty in understanding how to pass pointers between cpp and nim. In this case I want to pass an array buffer to the nth_element function by using any available strategy (in the example I have tried using pointers but I did not succeeded).
Is there a way of doing that?
Thanks in advance
Thanks, this works:
{.emit:"""
#include <algorithm>
} """.}
proc nth_element*(array: ptr float32, size: int, n: int) {.importcpp: "nth_element(@)".}
var arr = newSeqfloat32
- for i in 0 ..< arr.len:
- arr[i] = i.float32
nth_element(addr arr[0], arr.len, 5)
However if I try to export the nth_element function and import from another module, I have an error:
.cache/nim/test1_d/@mtest1.nim.cpp: In function ‘void NimMainModule()’:
Error: execution of an external compiler program 'g++ -c -std=gnu++17 -funsigned-char -w -fmax-errors=3 -fpermissive -pthread -I/home/....../.choosenim/toolchains/nim-2.0.4/lib -I/home/....development/vex-core/tests -o /home/...../.cache/nim/test1_d/@mtest1.nim.cpp.o /home/...../.cache/nim/test1_d/@mtest1.nim.cpp' failed with exit code: 1
it seems it cannot find the cpp declaration from the importing module.. how can I make that declaration available? Or should I compile this module first and import it compiled?
proc nth_element[T](first, nth, last: ptr T) {.header: "<algorithm>", importcpp: "std::nth_element(@)".}
proc nthElement*[T](x: var openArray[T]; nth: int) =
nth_element(x[0].addr, x[nth].addr, cast[ptr T](cast[uint](x[^1].addr) + sizeof(T).uint))
when isMainModule:
var x = [4, 3, 2, 1]
nthElement(x, 2)
echo x
var y = [5, 4, 3, 2, 1]
nthElement(y.toOpenArray(1, 4), 2)
echo y