Last active
March 15, 2023 19:30
-
-
Save Cheesebaron/9876783 to your computer and use it in GitHub Desktop.
C# to Java object wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class JavaHolder : Java.Lang.Object | |
{ | |
public readonly object Instance; | |
public JavaHolder(object instance) | |
{ | |
Instance = instance; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public static class ObjectExtensions | |
{ | |
public static TObject ToNetObject<TObject>(this Java.Lang.Object value) | |
{ | |
if (value == null) | |
return default(TObject); | |
if (!(value is JavaHolder)) | |
throw new InvalidOperationException("Unable to convert to .NET object. Only Java.Lang.Object created with .ToJavaObject() can be converted."); | |
TObject returnVal; | |
try { returnVal = (TObject) ((JavaHolder) value).Instance; } | |
finally { value.Dispose(); } | |
return returnVal; | |
} | |
public static Java.Lang.Object ToJavaObject<TObject>(this TObject value) | |
{ | |
if (Equals(value, default(TObject)) && !typeof(TObject).IsValueType) | |
return null; | |
var holder = new JavaHolder(value); | |
return holder; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I have two questions:
Java.Lang.Object
? Does it come from IKVM?java.lang.Object
?