如何 SWIG std::string& to C# ref string
How to SWIG std::string& to C# ref string
我正在尝试将std::string
引用的C 功能转换为C#。
我的API看起来像这样:
void GetStringDemo(std::string& str);
理想情况下,我想从c#
那里看到这样的东西void GetStringDemoWrap(ref string);
我知道我需要为此创建一个Typemap,并且我尝试使用std_string.i文件尝试了一些事情,但是我认为我不会到达任何地方。有人有任何例子吗?我是Swig和C#的新手,所以我无法提出任何真正的想法。
以防万一有人在将来寻找这个,我为c#创建了std_string.i。似乎对我有用。请注意,我将裁判员更改为外面,因为在我的情况下这更合适,但裁判也应该工作。
我拨打了%files in .i file
/* -----------------------------------------------------------------------------
* std_string_ref.i
*
* Typemaps for std::string& and const std::string&
* These are mapped to a C# String and are passed around by reference
*
* ----------------------------------------------------------------------------- */
%{
#include <string>
%}
namespace std {
%naturalvar string;
class string;
// string &
%typemap(ctype) std::string & "char**"
%typemap(imtype) std::string & "/*imtype*/ out string"
%typemap(cstype) std::string & "/*cstype*/ out string"
//C++
%typemap(in, canthrow=1) std::string &
%{ //typemap in
std::string temp;
$1 = &temp;
%}
//C++
%typemap(argout) std::string &
%{
//Typemap argout in c++ file.
//This will convert c++ string to c# string
*$input = SWIG_csharp_string_callback($1->c_str());
%}
%typemap(argout) const std::string &
%{
//argout typemap for const std::string&
%}
%typemap(csin) std::string & "out $csinput"
%typemap(throws, canthrow=1) string &
%{ SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, $1.c_str());
return $null; %}
}
我需要定义const std :: string&amp;的原因是因为Swig会感到困惑并覆盖const std :: string&amp;还有类型图。因此,我明确地告诉我不要在我的情况下覆盖(您可能有其他用例)
对于Python,我创建了类似的东西:
%typemap(argout)std::string&
{
//typemap argout std::string&
PyObject* obj = PyUnicode_FromStringAndSize((*$1).c_str(),(*$1).length());
$result=SWIG_Python_AppendOutput($result, obj);
}
%typemap(argout) const std::string &
%{
//argout typemap for const std::string&
%}
%typemap(in, canthrow=1) std::string & (std::string temp)
%{
//typemap in
$1 = &temp;
%}
在Alex的答案中,std::string temp
应该位于顶部,以便SWIG如果您有多个OUT put。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 将Ref对象作为类成员
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为什么我的 std::ref 无法按预期工作?
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何将 Eigen::Ref 与 pybind11 一起使用?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何@ref同一方法的不同变体?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何 SWIG std::string& to C# ref string
- 在 GCC 4.x / C++11 中是否对 std::string ref 计数