当前位置:网站首页>SWIG教程《四》-go语言的封装

SWIG教程《四》-go语言的封装

2022-08-10 14:31:00 阿酷尔工作室

以Go 封装为例

go语言不支持直接调用C或者C++语言,虽然通过cgo转接go可以实现对c的调用,但是调用过程各种数据类型之间无法还是无法直接转换,使用起来也不是很方便,而swig刚好能够填补这个空白

而且只要是go 1.2之后的版本,可以通过go build直接使用swig生成的源码

虽然swig会尽量将C、C++封装成go代码,但是由于两种语言之间的不同,还是会有部分改动在里面,比如const类型通过只对外提供Get接口来实现,通过defer来实现对对象内存的管理等。

为了能够实现go->c++->go这种形式的调用,必须借助代理模式,代理模式必须在指令文件中完成一下内容

  1. 先在模块上声明使用代理模式
%module(directors="1") modulename
  1. 在需要设置代理的类上指定代理
%feature("director") FooBarAbstruct;

导入额外的模块

%go_import("fmt", _ "unusedPackage", rp "renamed/package")
%insert(go_wrapper) %{
    func foo() {
    fmt.Println("Some string:", rp.GetString())

// Importing the same package twice is permitted,
// Go code will be generated with only the first instance of the import.
%go_import("fmt")
%insert(go_wrapper) %{
    func bar() {
    fmt.Println("Hello world!")
    } 
%}

使用说明

Swig 给出选项,并指出需要封装的文件,就可以对指定的文件进行封装。

where filename is a SWIG interface file or a C/C++ header file

swig [ options ] filename
swig
Generate bindings between C / C++ code and various high level languages such as Javascript, Python, C#, and more.It uses special .i or .swg files to generate the bindings (C/C++ with SWIG directives, then outputs a C/C++ file that contains all of the wrapper code needed to build an extension module.

 - Generate a binding between C++ and Python:
   swig -c++ -python -o {{path/to/output_wrapper.cpp}} {{path/to/swig_file.i}}

 - Generate a binding between C++ and Go:
   swig -go -cgo -intgosize 64 -c++ {{path/to/swig_file.i}}

 - Generate a binding between C and Java:
   swig -java {{path/to/swig_file.i}}

 - Generate a binding between C and Ruby and prefix the Ruby module with {{foo::bar::}}:
   swig -ruby -prefix "{{foo::bar::}}" {{path/to/swig_file.i}}
原网站

版权声明
本文为[阿酷尔工作室]所创,转载请带上原文链接,感谢
https://mdnice.com/writing/7919ef3afe2d499f90fd35f891d3040f