我在C ++中有一个自定义异常,它将 std :: vector 的 MyCustomClass 对象作为参数。
我正在使用swig将我的C ++项目翻译成C#。要处理C ++和C#中的异常,需要编写一些填充代码:
%insert(runtime) %{
// Code to handle throwing of C# CustomApplicationException from C/C++ code.
// The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
// and the equivalent customExceptionCallback instance is customDelegate
typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
CSharpExceptionCallback_t customExceptionCallback = NULL;
extern "C" SWIGEXPORT
void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
customExceptionCallback = customCallback;
}
// Note that SWIG detects any method calls named starting with
// SWIG_CSharpSetPendingException for warning 845
static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
customExceptionCallback(msg);
}
%}
%pragma(csharp) imclasscode=%{
class CustomExceptionHelper {
// C# delegate for the C/C++ customExceptionCallback
public delegate void CustomExceptionDelegate(string message);
static CustomExceptionDelegate customDelegate =
new CustomExceptionDelegate(SetPendingCustomException);
[global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
public static extern
void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
static void SetPendingCustomException(string message) {
SWIGPendingException.Set(new CustomApplicationException(message));
}
static CustomExceptionHelper() {
CustomExceptionRegisterCallback(customDelegate);
}
}
static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
%}
随着自定义C#异常:
// Custom C# Exception
class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
}
SWIG接口代码:
%typemap(throws, canthrow=1) std::out_of_range {
SWIG_CSharpSetPendingExceptionCustom($1.what());
return $null;
}
%inline %{
void oddsonly(int input) throw (std::out_of_range) {
if (input%2 != 1)
throw std::out_of_range("number is not odd");
}
%}
(来自http://www.swig.org/Doc3.0/CSharp.html#CSharp_exceptions)
这适用于基本异常(该示例将字符串作为参数),但是现在我正在尝试传递对象的向量,我正在撞墙。我曾试图使用编组,但我不清楚它是如何工作的,或者甚至是我在这种情况下应该尝试的那种。
有没有人这样做过,或类似的东西?