【问题标题】:Creating a SWIG typemap for C++ overloaded functions为 C++ 重载函数创建 SWIG 类型映射
【发布时间】:2019-01-09 20:18:22
【问题描述】:

我想知道如何为重载函数创建 SWIG 类型映射。

MyBindings.h

static void test(t_string *s)
{
    std::cout << "first : " << s->name << '\n');
}

static void test(t_string *s, t_string *s2)
{
    std::cout << "first : " << s->name << '\n');
    std::cout << "second : " << s2->name << '\n');
}

MyBindings.i

%module my
%{
    #include "MyBindings.h"
%}

%include <stl.i>
%include <exception.i>
%include <typemaps.i>
/* convert the input lua_String to t_string* */
%typemap(in) t_string*
{
    if (!lua_isstring(L, $input))
        SWIG_exception(SWIG_RuntimeError, "argument mismatch: string expected");
    $1 = makestring(lua_tostring(L, $input));
}

如果我在 Lua 中调用 test()

my.test("abc", "def");

我收到以下错误:

Wrong arguments for overloaded function 'test'
  Possible C/C++ prototypes are:
    test(t_string *)
    test(t_string *,t_string *)

我应该如何更正我的类型图以使其正常工作?

【问题讨论】:

  • 要测试的参数应该是 std::string 还是 [const] char*?我认为 SWIG 的整个想法是避免为 LUA 等语言编写接口代码?
  • @RichardHodges 如果我将t_string 替换为std::string 会起作用吗?
  • 我认为这就是 SWIG 的重点——自动为 c++ 对象提供其他语言接口。
  • 您的示例非常不完整,并且充满了语法错误。 -1

标签: c++ lua swig


【解决方案1】:

这是一个典型的 RTFM 案例。见11.5.2 "typecheck" typemap

如果你定义了新的“in”类型映射并且你的程序使用了重载的方法,你还应该定义一个“typecheck”类型映射的集合。更多详细信息请参见Typemaps and overloading 部分。

与您的问题一样,您的头文件中缺少包含保护。我刚刚制作了自己的t_string.h,因为我不知道这是从哪里来的。 test 函数不能是静态的,因为毕竟你想从这个翻译单元之外引用它们,而当它们有 internal linkage 时这是不可能的。

MyBindings.h

#pragma once
#include <iostream>
#include "t_string.h"

void test(t_string *s)
{
    std::cout << "first : " << s->name << '\n';
}

void test(t_string *s, t_string *s2)
{
    std::cout << "first : " << s->name << '\n';
    std::cout << "second : " << s2->name << '\n';
}

MyBindings.i

%module my
%{
    #include "MyBindings.h"
%}

/* convert the input lua_String to t_string* */
%typemap(typecheck) t_string* {
    $1 = lua_isstring(L, $input);
}
%typemap(in) t_string* {
    $1 = makestring(lua_tostring(L, $input));
}
%typemap(freearg) t_string* {
    freestring($1);
}
%include "MyBindings.h"

test.lua

local my = require("my")
my.test("abc", "def")

调用示例:

$ swig -c++ -lua MyBindings.i
$ clang++ -Wall -Wextra -Wpedantic -I /usr/include/lua5.2 -shared -fPIC MyBindings_wrap.cxx -o my.so -llua5.2
$ lua5.2 test.lua
first : abc
second : def

【讨论】:

  • 完美运行。非常感谢你,我很抱歉我的问题很糟糕。
  • @ZackLee 如果您删除语法错误,将缺少的详细信息添加到MyBindings.i,并添加指向提供t_string 的库的链接,我可以将我的反对票转换为赞成票。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多