dongzexi5125 2018-07-11 02:57
浏览 104
已采纳

使用CGO动态选择正确的操作系统和处理器架构

I have access only to a linux and darwin distributions of dynamically linked shared libraries.

Following is how I've integrated the library with Golang

// #cgo LDFLAGS: -L${SRCDIR}/build -lprocessing_lib
// #include "Processing-bridge.h"
// #include <stdlib.h>
import "C"
import "unsafe"

type ProcessorWrapper struct {
    ptr unsafe.Pointer
}

func init() {
    pr.ptr = C.NewProcessor()
}

func GetDefault() (id int, name string) {
    var default = C.GetDefault(pr.ptr)
    id = int(default.materialId)
    name = C.GoString(default.name)
    return
}

This works perfectly fine when I copy the matching library under the build/ folder.

I'm trying to make this as a go gettable library , where it could work on both linux and darwing architectures.

Problem I'm having is to tell go compiler to pick the right library for the matching GOOS and GOARCH.

I tried having a folder structure like below

build/darwing/libprocessing_lib.so
build/linux/libprocessing_lib.so

And modified the LDFLAGS as below

// #cgo LDFLAGS: -L${SRCDIR}/build/${GOOS} -lprocessing_lib

However it doesn't recognise ${GOOS} and replace it with the correct value.

Is there a way to achieve this dynamic library pickup feature?

  • 写回答

2条回答 默认 最新

  • doudansui6650 2018-07-11 05:14
    关注

    Found an easy way to achive this without creating multiple files by looking at the go source code it self cgo

    // #cgo darwin LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib
    // #cgo linux LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib
    

    we can also pass the Architecture if needed like below

    // #cgo darwin,arm64 LDFLAGS: -L${SRCDIR}/build/darwin -lprocessing_lib
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错