如何在 SWIG 中包装使用自定义引用类型的 C++ 函数?

首先,我可以包装使用自定义字符串类型的 C++ 函数。这是我如何做的。

这是我的 C++ 函数。

static void my_func(t_string message) {
    do_something(message.c_str());
}

这是 SWIG 类型映射。

%typemap(in) (t_string message)
{
    if (!lua_isstring(L, 1)) {
      SWIG_exception(SWIG_RuntimeError, "argument mismatch: string expected");
    }
    $1 = lua_tostring(L, 1);
}

虽然这似乎可以很好地工作,但我想知道是否可以包装 my_func(t_string &message)my_func(const t_string &message)

我问这个问题的原因是因为我认为通过引用传递字符串会比传值快一点,因为我可以避免不必要地复制字符串。

如果我对此有误,请告诉我。

点赞
用户1944004
用户1944004

一件事情需要注意:我不认为为了额外的性能提高而通过引用传递值值得麻烦,因为总的性能可能会受限于解释器类型和C++类型之间的转换。此外,由于当今的移动语义,您实际上可能不会获得任何性能提高,参见传递const std :: string&作为参数的日子已经过去了吗?

SWIG将引用视为指针并将其初始化为nullptr。这意味着您必须new一个字符串,将其存储在参数中,并定义一个额外的freearg类型映射以再次释放已分配的内存。

%模块参考

%{
#include <iostream>
#include <string>

using t_string = std :: string;

static void my_func(const t_string&message){
    std :: cout << message << '\ n';
}
%}

%include“exception.i”

%typemap(in)(const t_string&message)
{
    if(!lua_isstring(L,1)){
      SWIG_exception(SWIG_RuntimeError,“参数不匹配:预期字符串”);
    }
    $ 1 = new t_string {lua_tostring(L,1)};
}

%typemap(freearg)(const t_string&message)
{
    delete $ 1;
}

void my_func(const t_string&message);
2018-06-15 10:37:23