从Python调用Go字符串返回函数



我试着调用这个

// cryptography.go
func getDecryptedMessage(message string, d int, prime1 int, prime2 int) *C.char {
///
//do something
/////
return C.CString("hello from go")
}
//app.py
lib = cdll.LoadLibrary("./cryptography.so")
class go_string(Structure):
_fields_ = [
("p", c_char_p),
("n", c_longlong)]
lib.getDecryptedMessage.restype = c_char_p
b = go_string(c_char_p(decryptedMsg), len(decryptedMsg))
print (lib.getDecryptedMessage(b, c.d,c.prime1, c.prime2))

它将打印:b"从开始你好"。结果应该是:你好,来自go

我用构建它

go build -buildmode=c-shared -o cryptography.so cryptography.go

有人能帮我吗?编辑:我认为一定有问题

lib.getDecryptedMessage.restype = c_char_p

这是一个较小的版本:

//app.py
from flask import Flask, jsonify
from flask import abort
from flask import make_response
from flask import request
from flask_cors import CORS
from ctypes import *
import ctypes
lib = cdll.LoadLibrary("./a.so")
lib.getMessage.restype = c_char_p
print(lib.getMessage())
//a.go
package main
import "C"
//export getMessage
func getMessage() *C.char {
return C.CString("hello from go")
}

它将返回:b'hello from go'

它将打印:b'hello from go'

这完全正常。C字符串具有基于字节的类型。

在Python 2中,bytesstr类型相同,因此Py2k应用程序将C字符串视为字符串。在Python 3中,bytes类型与str类型不同。要将bytes转换为str,必须根据其编码对其进行解码。一般来说,如果可能的话,你可能会考虑尽量避免解码它,但如果必须解码,你必须告诉Python解码器它是如何编码的:

print(lib.getMessage().decode('utf-8'))

例如。(Go本身使用utf-8编码,但其他C项目可能不使用任何合理的编码。(

最新更新