从 Python 调用 Go string-return 函数
Call Go string-return function from Python
我试着叫这个
// 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'。
结果应该是: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")
}
它会 return: b'你好'
It will print: b'hello from go'
.
这是完全正常的。 C 字符串具有基于字节的类型。
在 Python 2 中,bytes
和 str
类型相同,因此 Py2k 应用程序将 C 字符串视为字符串。在Python3中,bytes
类型不同于str
类型。要将 bytes
转换为 str
,您必须根据其编码对其进行解码。通常,您可能会考虑尽可能避免对其进行解码,但如果必须对其进行解码,则必须告诉 Python 解码器它是如何编码的:
print(lib.getMessage().decode('utf-8'))
例如。 (Go 本身使用 utf-8 编码,但其他 C 项可能不使用任何合理的编码。)
我试着叫这个
// 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'。 结果应该是: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")
}
它会 return: b'你好'
It will print:
b'hello from go'
.
这是完全正常的。 C 字符串具有基于字节的类型。
在 Python 2 中,bytes
和 str
类型相同,因此 Py2k 应用程序将 C 字符串视为字符串。在Python3中,bytes
类型不同于str
类型。要将 bytes
转换为 str
,您必须根据其编码对其进行解码。通常,您可能会考虑尽可能避免对其进行解码,但如果必须对其进行解码,则必须告诉 Python 解码器它是如何编码的:
print(lib.getMessage().decode('utf-8'))
例如。 (Go 本身使用 utf-8 编码,但其他 C 项可能不使用任何合理的编码。)