参考:https://blog.csdn.net/weixin_42357472/article/details/117533537
https://tech.meituan.com/2022/04/21/cross-language-call.html
https://www.jianshu.com/p/346ac40ac2c3
1、str_print.h
#pragma once
#include
class StrPrint {
public:
void print(const std::string& text);
};
2、str_print.cpp
#include
#include "str_print.h"
void StrPrint::print(const std::string& text) {
std::cout << text << std::endl;
}
3、c_wrapper.cpp
Python、Java支持调用C接口,但不支持调用C++接口,因此对于C++语言实现的接口,必须转换为C语言实现。为了不修改原始C++代码,在C++接口上层用C语言进行一次封装
#include "str_print.h"
extern "C" {
void str_print(const char* text) {
StrPrint cpp_ins;
std::string str = text;
cpp_ins.print(str);
}
}
4、编译生成动态库:
g++ -o libstr_print.so str_print.cpp c_wrapper.cpp -fPIC -shared
# -*- coding: utf-8 -*-
import ctypes
# 加载 C lib
lib = ctypes.cdll.LoadLibrary("./libstr_print.so")
# 接口参数类型映射
lib.str_print.argtypes = [ctypes.c_char_p]
lib.str_print.restype = None
# 调用接口
lib.str_print(b'Hello World')
***传递中文
‘aaHello 你好’.encode(‘gbk’)
# -*- coding: utf-8 -*-
import ctypes
# 加载 C lib
lib = ctypes.cdll.LoadLibrary("./libstr_print.so")
#接口参数类型映射
# lib.str_print.argtypes = [ctypes.c_char_p]
# lib.str_print.restype = None
# 调用接口
bb = lib.str_print('aaHello 你好'.encode('utf-8'))
bb = lib.str_print('aaHello 你好'.encode('gbk'))
参考:https://blog.csdn.net/qq_41134008/article/details/105574136
https://blog.csdn.net/ns2250225/article/details/45559631
*创建箭头这4个文件结构,其他是python setup.py install 后生成的
1、init.py
# -*- coding: utf-8 -*-
import ctypes
import os
import sys
dirname, _ = os.path.split(os.path.abspath(__file__))
lib = ctypes.cdll.LoadLibrary(dirname + "/libstr_print.so")
lib.str_print.argtypes = [ctypes.c_char_p]
lib.str_print.restype = None
def str_print(text):
lib.str_print(text)
2、setup.py
from setuptools import setup, find_packages
setup(
name="strrprint",
version="1.0.0",
packages=find_packages(),
include_package_data=True,
description='str print',
author='xxx',
package_data={
'strprint': ['*.so']
},
)
3、MANIFEST.in
include strprrint/libstr_print.so
4、打包安装
python setup.py install
5、引用加载包测试
# -*- coding: utf-8 -*-
import sys
from strrprint import *
str_print(b'Hello py')