我正在尝试将带有 std::string
引用的 C++ 函数转换为 C#。
我的 API 如下所示:
void GetStringDemo(std::string& str);
理想情况下,我希望从 C# 中看到类似的东西
void GetStringDemoWrap(ref string);
我知道我需要为此创建一个类型映射,并且我通过使用 std_string.i 文件尝试了一些东西,但我认为我没有任何进展。有没有人有任何例子。我是 Swig 和 C# 的新手,所以我无法提出任何真正的想法。
最佳答案
以防万一有人在将来寻找这个,我为 C# 创建了这样的 std_string.i。似乎对我有用。请注意,我将 ref 更改为 out 因为它更适合我的情况,但 ref 也应该有效。
我从 .i 文件中调用了 %include "std_string.i"
/* -----------------------------------------------------------------------------
* 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& 定义 argout 的原因是因为 SWIG 会混淆并使用类型映射覆盖 const std::string&。所以我明确告诉它不要覆盖我的情况(你可能有不同的用例)
对于 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&
%}
关于c# - 如何将 std::string& SWIG 转换为 C# 引用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13022051/