使用Swig为C ++代码构建C#包装器时,是否可以将代码添加到现有方法中? [英] Is it possible to add code to an existing method when using Swig to build a C# wrapper for C++ code?

查看:39
本文介绍了使用Swig为C ++代码构建C#包装器时,是否可以将代码添加到现有方法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Swig包装C ++代码时,可以将方法添加到使用%extend 的本机C ++类型.可以使用 将方法添加到C#包装器类%typemap(cscode).

When using Swig to wrap C++ code, it is possible to add methods to the native C++ type using %extend. It is possible to add methods to the C# wrapper class using %typemap(cscode).

包装类中已经存在一种方法,是否可以添加其他代码行?

Where a method already exists in the wrapper class, is there a way to add additional lines of code?

例如,我的C#包装器方法如下:

For example, my C# wrapper method looks like this:

  public void ItemChanged(CollectionObject collectionObject, string propertyName) {
    mynamespacePINVOKE.mynamespace_DataObjectCollection_ItemChanged(swigCPtr, CollectionObject.getCPtr(collectionObject), propertyName);
    if (mynamespacePINVOKE.SWIGPendingException.Pending) throw mynamespacePINVOKE.SWIGPendingException.Retrieve();
  }

我想添加一行代码:

  public void ItemChanged(CollectionObject collectionObject, string propertyName) {
    mynamespacePINVOKE.mynamespace_DataObjectCollection_ItemChanged(swigCPtr, CollectionObject.getCPtr(collectionObject), propertyName);
    if (mynamespacePINVOKE.SWIGPendingException.Pending) throw mynamespacePINVOKE.SWIGPendingException.Retrieve();
    **insert my line of code here**
  }

推荐答案

要编写自己的版本,您需要确保它不会与默认版本冲突.我认为最简单的方法是使用%csmethodmodifiers %rename 隐藏默认包装版本,从而使 ItemChanged 私有/受保护得到生成.一旦被隐藏.

In order to write your own version you're going to need to make sure it doesn't clash with the default one. I think the easiest way to do this would be to make ItemChanged private/protected using %csmethodmodifiers and %rename to hide the default wrapped version that gets generated. Once it's hidden.

然后,您可以使用cscode类型映射安全地编写自己的 ItemChanged 版本,该类型映射首先调用私有版本,然后根据需要调用其他代码.

You can then safely write your own version of ItemChanged using a cscode typemap that firstly calls the private version and then calls your additional code as you desire.

这是迄今为止解决问题的最干净的方法-您唯一可以将代码直接注入到生成的代码中的方法是作为参数/返回值编组的一部分-设置传入的参数,在处理或处理返回值后进行清理.弄乱其中一个类型图以注入一些代码会很混乱.

This is by far the cleanest way of solving the problem - the only way you're able to inject code directly into the generated code is as part of the argument/return value marshalling - setting up the arguments that get passed in, cleaning up after or handling the return value. Messing with one of those typemaps to inject some code would be fairly messy.

这篇关于使用Swig为C ++代码构建C#包装器时,是否可以将代码添加到现有方法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆