当前位置:网站首页>SWIG tutorial "four" - package of go language

SWIG tutorial "four" - package of go language

2022-08-10 14:59:00 Akure Studio

以Go 封装为例

goThe language does not support direct invocationC或者C++语言,虽然通过cgo转接go可以实现对c的调用,However, there is no or no direct conversion between the various data types of the calling process,使用起来也不是很方便,而swigJust enough to fill this gap

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

虽然swig会尽量将C、C++封装成go代码,But due to the difference between the two languages,There will still be some changes in there,比如constTypes are only available externallyGet接口来实现,通过deferTo realize the management of object memory, etc.

为了能够实现go->c++->gocall of this form,Proxy mode must be used,The proxy mode must complete the following content in the directive file

  1. First declare the use of proxy mode on the module
%module(directors="1") modulename
  1. Specify the proxy on the class where the proxy needs to be set
%feature("director") FooBarAbstruct;

Import additional modules

%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 给出选项,And indicate the files that need to be encapsulated,The specified file can be encapsulated.

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}}
原网站

版权声明
本文为[Akure Studio]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101431161530.html