dongwei1954 2019-02-20 18:46
浏览 75

使用SWIG进行C ++编程:如何将C ++指针传递给Go? [重复]

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>
  • 写回答

1条回答 默认 最新

  • dongmei3498 2019-02-20 23:56
    关注

    @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]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭