c++ - SWIG:如何包装一个引用 int64_t 作为参数的函数?
问题描述
我的接口文件TestRef.i
:
%module test_ref
%{
#include <iostream>
%}
%include <stdint.i>
%include <typemaps.i>
%inline %{
struct Result {
uint64_t len;
void* data;
};
Result read(int64_t& idx) {
std::cout << idx << std::endl; // just to use idx
idx++;
return Result{1, nullptr};
}
void set_value(double& a) {
a = 42.;
}
%}
%apply int64_t& INOUT { int64_t& idx };
%apply double& INOUT { double& a };
void set_value(double& a);
我的目标是调用read()
,它通过引用参数返回一个 C 结构(实际上是打包的)和一个 int64_t。
这是我的构建方式:
$ swig -python -c++ -I/usr/include TestRef.i
$ g++ -fPIC -c TestRef_wrap.cxx -I/opt/rh/rh-python38/root/usr/include/python3.8 -std=c++17 -O3
$ g++ -shared TestRef_wrap.o -o _test_ref.so -lrt
这是我得到的错误:
>>> import test_ref
>>> idx = 1000
>>> p = test_ref.read(idx)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 79, in read
return _test_ref.read(idx)
TypeError: in method 'read', argument 1 of type 'int64_t &'
一些帖子建议引用将被“退回”,所以我应该这样做:
>>> p, idx = test_ref.read(idx)
但同样的错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 79, in read
return _test_ref.read(idx)
TypeError: in method 'read', argument 1 of type 'int64_t &'
然后,我找到了这个帖子。
我试过(TestRef.i
上面已经包含set()
):
>>> a = 0.0
>>> a = set_value(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hc/test/cpp/test_ref.py", line 66, in set_value
return _test_ref.set_value(a)
TypeError: in method 'set_value', argument 1 of type 'double &'
我正在使用 SWIG 4.0。
解决方案
根据这个帖子,[t]he typemap must also be declared before SWIG parses test
。
改变我TestRef.i
的
%module test_ref
%{
#include <iostream>
%}
%include <stdint.i>
%include <typemaps.i>
%apply int64_t& INOUT { int64_t& idx };
%apply double& INOUT { double& a };
%inline %{
struct Result {
uint64_t len;
void* data;
};
Result read(int64_t& idx) {
std::cout << idx << std::endl; // just to use idx
idx++;
return Result{1, nullptr};
}
void set(double& a) {
a = 42.;
}
作品:
>>> import test_ref
>>> idx = 1024
>>> p, idx = test_ref.read(idx)
1024
>>> print(idx)
1025
>>>
推荐阅读
- python - Python shell 日志命令未显示在 docker/kubernetes pod 中
- java - 我们如何在 weblogic 服务器中获取历史线程转储
- mysql - mysql - 在存储过程动态查询中使用 Concat
- android-studio - CommandInvokationFailure:重新打包资源失败。Unity MAC 构建问题
- sql-server - 我需要这个函数的postgresql版本
- silverstripe - 服务器迁移后,Silverstripe 4 在尝试上传文件时抛出错误
- visual-studio - 如何在 Xaml 的网格中放置边框?
- javascript - 消耗大量内存的 HTML 页面
- sql - 具有多值属性的 SQLite 数据库
- java - Selenium 和 Java:如何在 WebElement 之后获取所有文本