dongyuelian9602 2018-01-30 17:34
浏览 99
已采纳

cgo godefs和Objective-C

I write a program on GoLang with inclusion Objective-C code (call some OSX API) via C GoLang's package and I need to pass variable of type T from Go code to Objective-C code and vice versa. T is structure (or other type). So I need to create compatible (in terms of memory layout) type/variable in GoLang and pass it to Objective-C via unsafe.Pointer casting. For generic C code I use godefs in such cases, but I unable to use godefs for Objective-C. If I try go tool cgo -godefs cgodefs.go

// This is "cgodefs.go" file
package tmp

/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#import <Cocoa/Cocoa.h>
*/
import "C"

type CGPoint C.CGPoint

I receive tons of errors:

In file included from /Users/unsacrificed/go/src/gui/cgodefs.go:10:
In file included from /System/Library/Frameworks/Cocoa.framework/Headers/Cocoa.h:12:
In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:8:
/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:503:1: error: expected identifier or '('
@class NSString, Protocol;
^
/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:505:9: error: unknown type name 'NSString'
typedef NSString * NSExceptionName NS_EXTENSIBLE_STRING_ENUM;
        ^
/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:506:9: error: unknown type name 'NSString'
typedef NSString * NSRunLoopMode NS_EXTENSIBLE_STRING_ENUM;
... (100000+ lines of errors)

Interested thing is that I can compile and run GoLang apps with Objective-C via C GoLang's package.

I report to GoLang but he says that

The cgo tool works with C, not Objective-C.

Is there any way to get GoLang equivalent (memory compatible) type for Objective-C type?

  • 写回答

1条回答 默认 最新

  • dongtang1966 2018-03-11 13:12
    关注

    Finally I found a solution. It is possible to do what I want. The only thing I missed: godefs ignores #cgo CFLAGS: -x objective-c line. Solution - pass required CFLAGS to go binary as arguments (-- -x objective-c). Working example:

    // +build ignore
    
    package tmp
    
    //go:generate go tool cgo -godefs -- -x objective-c cgodefs.go
    
    //#import <Cocoa/Cocoa.h>
    import "C"
    
    type CGPoint C.CGPoint
    

    output:

    // Created by cgo -godefs - DO NOT EDIT
    // cgo -godefs -- -x objective-c cgodefs.go
    
    package tmp
    
    type CGPoint struct {
        X   float64
        Y   float64
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数据库原理及应用上机练习题
  • ¥30 征集Python提取PDF文字属性的代码
  • ¥15 如何联系真正的开发者而非公司
  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 (求远程解决)深信服vpn-2050这台设备如何配置才能成功联网?