我正在尝试在 C# 中为 C++ 库生成包装器,并使用生成的 C3 包装器来开发客户端应用程序。
C++ 类:
namespace ns {
class ISampleInterface {
public:
virtual ~ISampleInterface() {}
virtual void fn(int cnt) = 0;
};
}
namespace ns {
class ISampleInterface2 {
public:
virtual ~ISampleInterface() {}
virtual void fn2(int cnt) = 0;
};
}
namespace ns {
class SampleClass {
public:
SampleClass() {}
~SampleClass() {}
void InputFunction(int count, ISampleInterface sampleInterface, ISampleInterface2& sampleInterface2){
}
ISampleInterface& OutputFunction(void) {
return null;
}
};
}
预期的 C# 代码:
namespace csNS {
public class SampleClass {
public void InputFunction(int count, out SampleInterface sampleInterface, out SampleInterface2 sampleInterface2) {
// some code
}
public SampleInterface OutputFunction() {
// some code
}
}
}
Swig接口(interface)声明:
%interface_custom("SampleInterfaceImpl", "SampleInterface", ns::ISampleInterface);
%interface_custom("SampleInterface2Impl", "SampleInterface2", ns::ISampleInterface2);
%Outparams(ns:ISampleInterface, SampleInterfaceImpl)
%Outparams(ns:ISampleInterface2, SampleInterface2Impl)
在上面的 C# 代码中,InputFunction 有 3 个参数。但是,为 SampleInterface 和 SampleInterface2 生成的实现不包含默认构造函数。因此我无法为这些接口(interface)创建对象。由于我无法在 C# 端实例化接口(interface),因此我想将 then 作为 out 参数传递给 CS 函数,然后将在 C++ 端初始化。因此,要修改在我定义的类型映射下面的 swig 编译期间生成的 cs 文件。
类型映射声明:
%define %Outparams(TYPE, InterfaceImpl)
%typemap (cstype) TYPE,
TYPE &,
TYPE *,
TYPE *& "out TYPE"
%enddef
使用上面的类型映射,我可以更改输入参数,但是,它也会更改函数返回值,而我无法控制这一点。
实际生成的cs代码:
namespace csNS {
public class SampleClass {
public void InputFunction(int count, out SampleInterface sampleInterface, out SampleInterface2 sampleInterface2) {
// some code
}
public out SampleInterface OutputFunction() {
// some code
}
}
}
我做错了什么???
最佳答案
我更改了类型映射声明,它起作用了。
对于类(class):
%typemap (cstype, out="TYPE") TYPE,
TYPE &,
TYPE *,
TYPE *& "out TYPE"
对于接口(interface):
%typemap (cstype, out="InterfaceImpl") TYPE,
TYPE &,
TYPE *,
TYPE *& "out InterfaceImpl"
CS 文件:
namespace csNS {
public class SampleClass {
public void InputFunction(int count, out SampleInterface sampleInterface, out SampleInterface2 sampleInterface2) {
// some code
}
public SampleInterfaceImpl OutputFunction() {
// some code
}
}
}
关于c# - 使用 SWIG 更改生成的 CS 函数中的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60095138/