问题
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?
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();
}
I'd like to add a line of code:
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**
}
回答1:
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.
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.
来源:https://stackoverflow.com/questions/11286913/is-it-possible-to-add-code-to-an-existing-method-when-using-swig-to-build-a-c-sh