You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python通过ctypes传入字符串调用C++导出encrypt函数的方法

C++动态库ctypes调用完整实现方案

调用失败的核心原因是ctypes仅兼容C语言标准ABI接口,直接返回C++std::string类型会出现类型不匹配、内存解析错误的问题,同时原C++代码存在内存泄漏、字符串缺少结束符的隐藏bug,完整可行方案如下:

1. 修正C++导出代码

将导出函数的参数、返回值全部改为C兼容的原生字符指针类型,修复原有代码bug,调整后代码如下:

#include <iostream>
#include <string>
using namespace std;

extern "C" {
    // 导出接口统一用C风格类型,保证ABI兼容
    const char* encrypt(const char* str) 
    {
        // 静态缓冲区复用,无需手动释放,避免内存泄漏
        // 缓冲区大小比支持的最大输入长度多1,用于存字符串结束符
        static char store[101]; 
        string temp = str;
        int length = temp.length();
        
        int disp = length, i = 0;
        char printChar;
        
        while(disp > 0) {
            printChar = *(str + length - disp);
            if ((printChar >= 65) && (printChar <= 90)) {
                if (printChar + disp > 90) {
                    printChar = ((printChar + disp) % 90) + 64;
                }else{
                    printChar += disp;
                }
            }
            else if ((printChar >= 97) && (printChar <= 122)) {
                if (printChar + disp > 122) {
                    printChar = ((printChar + disp) % 122) + 96;
                }else{
                    printChar += disp;
                }
            }
            store[i] = printChar;
            disp -= 1;
            i += 1;
        }
        store[i] = '\0'; // 必须补C字符串结束符,否则返回结果乱码
        return store;
    }
}

说明:extern "C"标记会强制编译器按C规则导出函数,避免C++名称修饰导致ctypes找不到函数入口

2. 编译生成动态链接库

根据你的操作系统,在代码文件所在目录执行对应编译命令:

  • Windows(MinGW环境):g++ -shared -fPIC -o encrypt_lib.dll encrypt.cpp -static-libgcc -static-libstdc++
  • Linux:g++ -shared -fPIC -o encrypt_lib.so encrypt.cpp
  • macOS:g++ -shared -fPIC -o encrypt_lib.dylib encrypt.cpp

3. Python端ctypes调用代码

加载动态库后必须显式声明函数的参数类型和返回值类型,避免ctypes默认按整数类型解析地址导致崩溃,代码如下:

import ctypes
import sys

# 按操作系统加载对应动态库
if sys.platform == "win32":
    encrypt_lib = ctypes.CDLL("./encrypt_lib.dll")
elif sys.platform == "linux":
    encrypt_lib = ctypes.CDLL("./encrypt_lib.so")
elif sys.platform == "darwin":
    encrypt_lib = ctypes.CDLL("./encrypt_lib.dylib")
else:
    raise RuntimeError("当前操作系统不支持")

# 显式声明函数签名,保证类型匹配
encrypt_lib.encrypt.argtypes = [ctypes.c_char_p]
encrypt_lib.encrypt.restype = ctypes.c_char_p

# 实现预期调用逻辑
if __name__ == "__main__":
    user_string = input()
    # Python字符串转C风格字节串传入
    input_bytes = user_string.encode("utf-8")
    result_bytes = encrypt_lib.encrypt(input_bytes)
    # C返回的字节串转回Python可打印的字符串
    result = result_bytes.decode("utf-8")
    print(result)

注意:当前C++代码默认支持最长100字符的输入,如果需要处理更长文本,把store数组的长度调大即可,比如改为static char store[4097]即可支持最长4096字符的输入。

内容的提问来源于stack exchange,提问作者Mayhul Jindal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 07:39:19