登录
首页 >  Golang >  Go问答

如何在restype中处理多个返回值的访问?

来源:stackoverflow

时间:2024-02-09 17:12:24 417浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《如何在restype中处理多个返回值的访问?》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我正在编写如下 go 程序:

package main

import (
    "c"
)

//export getdata
func getdata(symbol string, day string, month string, year string) (string, string) {
    return "a", "b"
}

func main() {

}

在python中,我正在这样做:

import ctypes
library = ctypes.cdll.loadlibrary('./deribit.so')
get_data = library.getdata

# make python convert its values to c representation.
get_data.argtypes = [ctypes.c_wchar, ctypes.c_wchar,ctypes.c_wchar,ctypes.c_wchar]
get_data.restype = [ctypes.c_wchar,ctypes.c_wchar]

d,c = get_data("symbol", "day","month","year")
print(d,c)

它给出了错误:

get_data.restype = ctypes.c_wchar,ctypes.c_wchar
TypeError: restype must be a type, a callable, or None

正确答案


来自cgo 文档

可以通过以下方式导出 go 函数以供 c 代码使用:

//export myfunction
func myfunction(arg1, arg2 int, arg3 string) int64 {...}

//export myfunction2
func myfunction2(arg1, arg2 int, arg3 string) (int64, *c.char) {...}

它们将在 c 代码中提供为:

extern GoInt64 MyFunction(int arg1, int arg2, GoString arg3);
extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);

在 _cgo_export.h 生成的标头中找到,位于任何前导码之后 从 cgo 输入文件复制。 具有多个返回值的函数 映射到返回结构的函数。

返回多个值的函数被映射到返回结构的函数。读取 _cgo_export.h 生成的标头以查看结构体定义;该文档不清楚结构定义是什么样的。我猜它只是包含按照函数返回顺序的所有返回值,以及一些未指定的自动生成的名称,但文档没有说明。

(上面代码中的 gostring 可能应该是 _gostring_;这是链接文档页面中唯一不带下划线编写 gostring 的部分。这可能是一个错误。)

但是,您还有其他问题,这两个问题都会阻止您调用 getdata 函数。

第一个问题是 go 字符串不是 char *。它有自己独立的类型。 c 代码可以通过 _gostring_ 类型和几个辅助函数与 go 字符串交互,但不支持从 go 外部创建 go 字符串。

第二个是,由于 go 垃圾回收的原因,非 go 代码如何与 go 内存指针交互有很多限制。限制之一是 go 代码不能将 go 字符串返回给非 go 代码,也不能返回任何包含指向 go 内存的指针的其他内容。您的 getdata 返回 go 字符串,因此无法从 go 外部调用它。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在restype中处理多个返回值的访问?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>