gpt4 book ai didi

c# - C++ -> C# 使用 SWIG : how to use default constructor for a class

转载 作者:行者123 更新时间:2023-11-30 20:00:56 26 4
gpt4 key购买 nike

我在 C++ 中有一个 TInt 类,它包含一个整数值并提供了一些方法。它还有一个接受 int 的默认构造函数,这允许我在 C++ 中说:

TInt X=3;

我想使用 SWIG 将这个类和其他类导出到 C#,但我无法弄清楚我需要做什么才能用 C# 编写同一行:

TInt X=3;

现在我收到预期错误“无法将‘int’隐式转换为‘TInt’”

事情更复杂,因为在其他类中也有接受 TInt 作为参数的方法。例如,TIntV 是一个包含 TInt 向量的类,并具有方法 Add(TInt& Val)。在 C# 中,我只能将此方法称为:

TIntV Arr;
Arr.Add(new TInt(3));

如有任何帮助,我们将不胜感激。

格雷戈尔

最佳答案

我找到了一个完整的解决方案,包括席欢的答案:

在 SWIG 的接口(interface)文件 (*.i) 中,我添加了以下行:

%typemap(cscode) TInt %{
//this will be added to the generated wrapper for TInt class
public static implicit operator TInt(int d)
{
return new TInt(d);
}
%}

这会将运算符添加到生成的 .cs 文件中。要记住的一件事(我花了一个小时来修复它)是此内容必须在导入 c++ 类的代码之前声明的接口(interface)文件中。

关于c# - C++ -> C# 使用 SWIG : how to use default constructor for a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com