python 接收c++的.so传的jsoncpp字符串
叮!快来看看我和文心一言的奇妙对话~点击链接 https://yiyan.baidu.com/share/57o6vGa3GY -- 文心一言,既能写文案、读文档,又能绘画聊天、写诗做表,你的全能伙伴!
要从 C++ 动态链接库 (.so 文件) 中接收 JSON 字符串并在 Python 中使用,我们可以使用 jsoncpp 库来生成 JSON 字符串,然后通过 ctypes 库在 Python 中调用 C++ 函数。以下是一个完整的示例,展示如何实现这一过程。
1. 创建 C++ 动态链接库
首先,我们需要创建一个 C++ 动态链接库,该库将生成一个 JSON 字符串并将其返回给 Python。
C++ 代码 (example.cpp)
cpp
#include <string>
#include <json/json.h>
extern "C" {
// 函数返回 JSON 字符串
const char* get_json_string() {
Json::Value root;
root["h"] = 1104;
root["w"] = 1920;
root["message"] = "OK";
root["code"] = 0;
Json::StreamWriterBuilder writer;
std::string json_str = Json::writeString(writer, root);
// 注意:返回的字符串指针必须在堆上分配,否则会失效
// 这里我们使用静态变量来保持字符串的生命周期
static std::string static_json_str;
static_json_str = json_str;
return static_json_str.c_str();
}
}
编译为动态链接库
使用以下命令编译 C++ 代码为动态链接库。确保你已经安装了 jsoncpp 库:
bash
g++ -shared -fPIC -std=c++11 example.cpp -o libexample.so -ljsoncpp
2. Python 代码调用动态链接库
接下来,编写 Python 代码来调用这个动态链接库并处理返回的 JSON 字符串。
Python 代码 (main.py)
python
import ctypes
import json
def main():
# 加载动态链接库
lib = ctypes.CDLL('./libexample.so')
# 指定返回类型为 const char*
lib.get_json_string.restype = ctypes.c_char_p
# 调用 C++ 函数
json_str = lib.get_json_string()
# 将 C 字符串转换为 Python 字符串
json_str = json_str.decode('utf-8')
try:
# 解析 JSON
data = json.loads(json_str)
print("Received data:", data)
print("Height:", data["h"])
print("Width:", data["w"])
print("Message:", data["message"])
print("Code:", data["code"])
except json.JSONDecodeError as e:
print("Error decoding JSON:", e)
if __name__ == "__main__":
main()
3. 运行 Python 代码
确保动态链接库 (libexample.so) 在 Python 可以找到的路径中,然后运行 Python 脚本:
bash
python3 main.py
注意事项
字符串生命周期:在 C++ 中返回字符串时,必须确保字符串的生命周期足够长。在这个例子中,我们使用了一个静态字符串来确保这一点。
JSON 库:确保安装了 jsoncpp 库,并在编译时链接该库。
错误处理:在 Python 中处理 JSON 解析错误和其他可能的异常。
跨平台:这种方法在 Linux 上运行良好。在 Windows 上,你需要使用 .dll 而不是 .so,并且可能需要调整编译命令。
通过这种方式,你可以轻松地在 Python 和 C++ 之间传递 JSON 数据。