有没有办法(typemap 或 pragma)将自定义 C# 类插入到生成的 C# 代码中?使用 %typemap(cscode)
很容易将代码添加到包装的 C++ 类中 - 但添加 C# 类并不明确...
例如,SWIG doc创建自定义异常说:
除了手工制作的 CustomApplicationException
之外,还必须使用上面的样板代码:
// Custom C# Exception
public class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
}
但是不清楚如何通过接口(interface)文件添加这个类。
最佳答案
有一个记录的 pragma 接近您想要的,%pragma(csharp) imclasscode
.这会将代码插入到生成的 modulePINVOKE.cs 文件中。
虽然我们在 SWIG 的源代码树中发现:
/* ----------------------------------------------------------------------------- * pragmaDirective() * * Valid Pragmas: * imclassbase - base (extends) for the intermediary class * imclassclassmodifiers - class modifiers for the intermediary class * imclasscode - text (C# code) is copied verbatim to the intermediary class * imclassimports - import statements for the intermediary class * imclassinterfaces - interface (implements) for the intermediary class * * modulebase - base (extends) for the module class * moduleclassmodifiers - class modifiers for the module class * modulecode - text (C# code) is copied verbatim to the module class * moduleimports - import statements for the module class * moduleinterfaces - interface (implements) for the module class * * ----------------------------------------------------------------------------- */ virtual int pragmaDirective(Node *n) {
因此,假设您对以下嵌套类感到满意:
%module test
%pragma(csharp) modulecode=%{
// Custom C# Exception
public class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
}
%}
在 module.cs 中完全符合您的要求。如果这还不够,那么我们将不得不开始寻找解决方法,并且在 SWIG 之外(但在同一源代码树中)手动编写小的独立代码块可能会变得更清晰、更简单。
如果你真的想进入解决方法领域,你可以(ab)使用 moduleclassmodifiers pragma 将东西插入全局命名空间,例如:
%module test
%pragma(csharp) moduleclassmodifiers=%{
// Custom C# Exception
public class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
}
public class%}
生成 test.cs:
using System;
using System.Runtime.InteropServices;
// Custom C# Exception
public class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
}
public class test {
}
关于c# - SWIG 和 C# : insert empty C# class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899785/