![](/img/trans.png)
[英]Search email body for string and return values after that string-return lines after pattern
[英]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'。 結果應該是:你好,來自 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 中, bytes
和str
類型相同,因此 Py2k 應用程序將 C 字符串視為字符串。 在 Python 3 中, bytes
類型與str
類型不同。 要將bytes
轉換為str
,您必須根據其編碼對其進行解碼。 通常,您可能會考慮盡量避免對其進行解碼,但如果必須對其進行解碼,則必須告訴 Python 解碼器它是如何編碼的:
print(lib.getMessage().decode('utf-8'))
例如。 (Go 本身使用 utf-8 編碼,但其他 C 項目可能不使用任何合理的編碼。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.