douyongdao4046 2018-03-08 10:17
浏览 102

从Go函数返回CGo String到Python程序

So i'm trying to return a string result from a go function to a python string. So far I am returning a *C.char from go and getting this into python, I am just having trouble de-referencing of the pointer, since this is something I am not familiar with in python.

Go part:

package main

import "C"

import (
    "fmt"
)

//export HelloGo
func HelloGo(a string) *C.char {
    fmt.Println("Go recieved:", a)
    return C.CString(fmt.Sprintf("Hello from Go, %s!", a))
}

func main() {}

Python part:

import ctypes as c

text = b"PYTHON MESSAGE"

lib = c.cdll.LoadLibrary("./hey.so")

class GoString(c.Structure):
    _fields_ = [("p", c.c_char_p), ("n", c.c_longlong)]

lib.HelloGo.argtypes = [GoString]
gs = GoString(text, len(text))
result = c.c_char_p(lib.HelloGo(gs))

print("Python reads:", result)

output:

Go recieved: PYTHON MESSAGE
Python reads: c_char_p(4607968)

I have tried using result.value and c_string_from(result), but these give me a segmentation fault. I have had no difficulty getting the result in a C program and understand I can write a Python extension to retrieve this but this seems a bit convoluted.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 高德地图点聚合中Marker的位置无法实时更新
    • ¥15 DIFY API Endpoint 问题。
    • ¥20 sub地址DHCP问题
    • ¥15 delta降尺度计算的一些细节,有偿
    • ¥15 Arduino红外遥控代码有问题
    • ¥15 数值计算离散正交多项式
    • ¥30 数值计算均差系数编程
    • ¥15 redis-full-check比较 两个集群的数据出错
    • ¥15 Matlab编程问题
    • ¥15 训练的多模态特征融合模型准确度很低怎么办