gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:09:17 25 4
gpt4 key购买 nike

我尝试称这个

// 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'hello from 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'

最佳答案

It will print: 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项目可能未使用任何明智的编码。)

关于python - 从Python调用Go字符串返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65248236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com