This question already has an answer here:
See code below and I will explain
int* Camera::retrieveDataPointerPerBuffer() {
int cameraData [10] = {1,2,3,4,5,6,7,8,9,10};
int* pSrc = cameraData;
return cameraData;
} //camera.cpp
The code above has int pointer pSrc pointing to array and then returned. This is a function in C++. Next, I am using SWIG to essentially wrap this C++ function, so that I can call it in Go. The following code demonstrates the function being called in Go.
func myCamera() {
cam := camera.NewCamera()
pSrc := cam.RetrieveDataPointerPerBuffer()
for i := 0; i < 10; i++ {
fmt.Println("%d", pSrc)
}
} //main.go
Note: I know that I cannot iterate pointers in Go. But is there any way?
Output: 0
Problems: How do you access the arrays elements via pointer from C++ to Go? Additional Information: This is a simplified version of a larger project I am working on. I must return this pointer, I cannot return a vector.
Let me know if you need me to clarify anything for you.
</div>
@JimB Thanks for all of your resources. I figured it out and this seems to do the trick.
int* Camera::retrieveDataPointerPerBuffer() {
int cameraData [10] = {1,2,3,4,5,6,7,8,9,10};
int* pSrc = cameraData;
return cameraData;
} //camera.cpp
Below contains the changes that I made
func myCamera() { //For Goroutine
cam := camera.NewCamera()
pSrc := cam.RetrieveDataPointerPerBuffer()
arraySize := 10
slice := (*[1 << 30]C.int)(unsafe.Pointer(pSrc))[:arraySize:arraySize]
fmt.Println(slice)
}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Follow Up Question: Would anyone mind explaining this line of code?
slice := (*[1 << 30]C.int)(unsafe.Pointer(pSrc))[:arraySize:arraySize]