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

如何在SWIG中实现Python整数到boost::multiprecision::cpp_int的转换?

解决Python整数转boost::multiprecision::cpp_int的SWIG调用问题

SWIG默认没有内置boost::multiprecision::cpp_int与Python整数之间的类型转换规则,需要在.i文件中添加**类型映射(typemap)**实现双向转换。

修改后的example.i文件

/* example.i */
%module example
%{
    #include <boost/multiprecision/cpp_int.hpp>

    using namespace boost::multiprecision;
    extern cpp_int factor(cpp_int n, int seed);
%}

// 处理Python整数 -> cpp_int的输入转换
%typemap(in) cpp_int {
    if (PyLong_Check($input)) {
        // 将Python整数转为字符串,再构造cpp_int(支持超大整数)
        PyObject* str_obj = PyObject_Str($input);
        const char* num_str = PyUnicode_AsUTF8(str_obj);
        $1 = cpp_int(num_str);
        Py_DECREF(str_obj);
    } else {
        PyErr_SetString(PyExc_TypeError, "参数1必须是整数类型");
        return NULL;
    }
}

// 处理cpp_int -> Python整数的输出转换
%typemap(out) cpp_int {
    $result = PyLong_FromString($1.str().c_str(), NULL, 10);
}

extern cpp_int factor(cpp_int n, int seed);

关键说明

  • 输入类型映射:通过字符串中转构造cpp_int,避免超大整数超出基础数值类型范围的问题。
  • 输出类型映射:将cpp_int转为字符串后,再生成Python整数对象。

重新编译扩展

  1. 重新生成SWIG包装代码:
swig -c++ -python example.i
  1. 编译生成Python扩展模块(以g++为例):
g++ -fPIC -shared example_wrap.cxx -o _example.so -lpython3.x -lboost_system

(替换python3.x为你实际的Python版本,比如python3.10)

完成后在Python中直接调用example.factor(4846403, 2)即可,无需手动转换类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:45:15