这是我的 SWIG 类型图:
%apply (float *INOUT, int) {(float *io1, int n1)};
%apply (float *INOUT, int) {(float *io2, int n2)};
这是我的功能:
void process(float *io1, int n1, float *io2, int n2)
{
for (int i = 0; i < n1; ++i)
{
io1[i] = io1[i] * 0.1;
io2[i] = io2[i] * 0.1;
}
}
我希望 process
函数获取 2 个表并返回 2 个表。
在Lua中,process
函数似乎返回2个表,但它只返回从第一个参数传递的相同的2个表。
例如,在 Lua 中,当我运行以下命令时:
local a, b = {3}, {4}
local c, d = process(a, b)
print(c[1], d[1])
我得到的结果:
0.3 0.3
但我期望:
0.3 0.4
我应该如何更改 SWIG 类型映射以使其按预期工作?
最佳答案
我无法用以下最小示例重现您的问题。
test.i
%module example
%{
#include "test.h"
%}
%include <typemaps.i>
%apply (float *INOUT, int) {(float *io1, int n1)};
%apply (float *INOUT, int) {(float *io2, int n2)};
%include "test.h"
test.h
#pragma once
void process(float *io1, int n1, float *io2, int n2);
test.c
#include "test.h"
void process(float *io1, int n1, float *io2, int n2) {
for (int i = 0; i < n1; ++i) {
io1[i] = io1[i] * 0.1;
io2[i] = io2[i] * 0.1;
}
}
test.lua
local example = require("example")
local a, b = {3}, {4}
local c, d = example.process(a, b)
print(c[1], d[1])
然后我使用编译并运行
$ swig -lua test.i
$ cc -fPIC -shared -I /usr/include/lua5.3/ test_wrap.c test.c -o example.so
$ lua5.3 test.lua
0.30000001192093 0.40000000596046
第 7 位十进制数字之后的垃圾值源于将 float
提升为 lua_Number
,默认情况下为 double
。
不管这一点,我看到了预期的0.3 0.4
。这意味着错误一定出现在您未显示的某些代码中。确保在解析 process
原型(prototype)之前%apply
类型映射,即在上面的示例中注意如何%apply
位于 %include "test.h"
之前。
关于lua - 如何为接受并返回 2 个表的函数创建 SWIG 类型映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296206/