栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

python ctypes调用c++ so库;python setuptools工具库打pypi包

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python ctypes调用c++ so库;python setuptools工具库打pypi包

参考: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、python调用c++ so库

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


5、python调用案例

# -*- 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'))

2、python setuptools工具库打包python包

参考: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')

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942641.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号