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

python ctypes调用c++ so库;python setuptools工具库打pypi包_第1张图片
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')

python ctypes调用c++ so库;python setuptools工具库打pypi包_第2张图片
***传递中文
‘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'))

python ctypes调用c++ so库;python setuptools工具库打pypi包_第3张图片

2、python setuptools工具库打包python包

参考:https://blog.csdn.net/qq_41134008/article/details/105574136
https://blog.csdn.net/ns2250225/article/details/45559631

python ctypes调用c++ so库;python setuptools工具库打pypi包_第4张图片
*创建箭头这4个文件结构,其他是python setup.py install 后生成的
python ctypes调用c++ so库;python setuptools工具库打pypi包_第5张图片
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')

python ctypes调用c++ so库;python setuptools工具库打pypi包_第6张图片

你可能感兴趣的:(知识点,python,c++,开发语言)