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

How to wrap a C++ function that uses referenced custom type in SWIG?

首先,我可以包装使用自定义字符串类型的 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");
    }
     = lua_tostring(L, 1);
}

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

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

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

提前一件事:我认为通过引用传递额外的性能是不值得的,因为整体性能可能主要由解释器类型和 C++ 类型之间的转换决定。此外,由于今天的移动语义,您实际上可能不会获得任何性能,请参见。 传递 const std::string & 作为参数的时代结束了吗?

SWIG 处理 references as pointers 并将它们初始化为 nullptr。这意味着您必须 new 建立一个字符串,将其存储在参数中并定义一个额外的 freearg 类型映射以再次摆脱分配的内存。

%module references

%{
#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, "argument mismatch: string expected");
    }
     = new t_string{lua_tostring(L, 1)};
}

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

void my_func(const t_string &message);