SWIG: generate additional (hand-rolled) Java class - swig

I'm using SWIG to generate a Java JNI wrapper for my DLL.
As part of it, I want to generate a custom exception class, but I want to provide the complete Java class implementation for my exception class myself.
I can of course just put my Java class in a separate file, but is it possible to embed such a hand-rolled Java class into a SWIG script?

Unless the class is an inner class of some sort you're pretty much left with writing it as a separate file since that's what it needs to be when you come to compile the Java.
I'm slightly puzzled why you would want to write your own pure Java exception class though - the normal thing to do with SWIG would be derive from std::exception, even if it's through a %inline directive and merge the C++ exception hierarchy with the Java one naturally and for free.
There is a workaround you could use if you really want (although I personally would neverdo it) to generate a pure Java class from the SWIG interface though:
%module test
%nodefaultctor MyException;
%typemap(javabody) MyException %{
// Java stuff goes here (or in javacode typemap)
%}
%typemap(javafinalize) MyException ""
%typemap(javadestruct) MyException ""
struct MyException {};
Which generates:
public class MyException {
// stuff goes here
}
But since that is clearly an ugly hack I'd strongly recommend avoiding it entirely and just writing the class like normal in your source distribution.

Related

How to write C++ constructor of cython extension type?

How do I modify the C++ class constructor that cython will generate from a Cython extension type that I've defined in a .pyx file wo that I don't incur the penalty of using def __cinit__(self)? Assume I am compiling to C++, not C.
What I would like to do is set the default values as I would in an initialization list in C++, and maybe run some code in the constructor without interacting with Python. It looks like the __cinit__ method runs after the C++ class members are initialized and the C++ constructor finishes running.
In this example, it says
Cython initializes C++ class attributes of a cdef class using the nullary constructor.
I assume this refers to the default constructor since the C++ constructor is a nullary constructor. I also assumes this happens with or without a __cinit__ method.
If the class you’re wrapping does not have a nullary constructor, you must store a pointer to the wrapped class and manually allocate and deallocate it. A convenient and safe place to do so is in the cinit and dealloc methods which are guaranteed to be called exactly once upon creation and deletion of the Python instance.
I have an existing class where I call Py_XDECREF on a member object in a loop inside of __dealloc__. This object holds pointers to Python objects. When I convert to C++ code, the annotated HTML shows no highlighted yellow text in the lines where the __dealloc__ method is defined. This is interesting because __dealloc__ is also defined using def.
When I try to initialize a member that is an instance of a Cython Extension that I defined (and did not create from wrapping C++ code), however, the __cinit__ method is highlighted in yellow.
def __cinit__(self):
self._member = MyCyExt()
I'm wondering if it's because I can't initialize a Cython Extension Type in pure C++. I don't know why that would be the case since Cython calls the nullary constructor by default.
This answer solves the problem, but it incurs the overhead I am trying to avoid. Is there a way to do this without incurring that overhead and actually writing the constructor itself in a .pyx file?

Call abstract java class from jruby with a generic

Currently facing an issue while writing a similar java class in Jruby.
Example:
In Java:
public class Client extends ClientConnection<ChannelType> {
//do some stuff
}
In Jruby:
class Client < Java::'package_name'::ClientConnection
//do some stuff
end
Don't know how to pass ChannelType class in Jruby code while rewriting the Client class
The short version is, you can't unfortunately.
The JRuby wiki explains it as such here (https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#beware-of-java-generics):
If a Java class is defined with Java generics, the types are erased during compilation for backwards compatibility. As a result, JRuby will have problems with automatic type conversion. For example, if you have a Map, it will be seen as a simple Map, and JRuby will not be able to determine the correct types using reflection.

How do I avoid conflicts between haxe Type class and C# Type class?

I am developing Haxe code that I convert in C# and insert into a Unity project.
The conversion works fine and I am able to use the generated class when I import it alone in Unity.
To make it work, I have to bring in Unity the whole generated src folder, including the Type.cs file.
However, when I import the "Post Processing Stack" (a basic Unity extension) I get errors due to name Conflicts. The Type class is also a basic C# class and It is used by the Post Processing scripts.
The haxe-Type takes priority and breaks the compilation:
Assets/PostProcessing/Runtime/PostProcessingBehaviour.cs(406,30): error CS1502: The best overloaded method match for `System.Collections.Generic.Dictionary<Type,System.Collections.Generic.KeyValuePair<UnityEngine.Rendering.CameraEvent,UnityEngine.Rendering.CommandBuffer>>.Add(Type, System.Collections.Generic.KeyValuePair<UnityEngine.Rendering.CameraEvent,UnityEngine.Rendering.CommandBuffer>)' has some invalid arguments
Assets/PostProcessing/Runtime/PostProcessingBehaviour.cs(406,34): error CS1503: Argument `#1' cannot convert `System.Type' expression to type `Type'
I don't know if it is possible to solve this issue by playing around with C#/Unity/Mono search paths.
I as wondering wether it is more appropriate to (optionally) wrap all haxe top-level classes into the haxe namespace, or a special haxe-defaultnamespace, or prefix them for example to class HType.
Name conflicts for this basic types are likely to emerge in many other contexts, not only in Unity.
I found the solution in the Haxe documentation for C#:
https://github.com/HaxeFoundation/HaxeManual/wiki/Haxe-C%23
-D no-root generate package-less haxe types in the haxe.root namespace to avoid conflicts with other types in the root namespace
This way, all the classes that were at global level will be generated under namespace haxe.root.

How to call a virtual method overridden in python from C++ using SWIG

My C++ class:
class Base {
public:
virtual void foo(int);
};
In the python module, I have a class that derives from above and overrides foo.
class PyDerived(Base):
...
def foo(self):
...
Then I create an object of this derived class using a factory method that is defined in python module like this:
def createObject():
m = PyDerived()
return m
With this PyObject in C++ code, I want to call foo and I want foo in python module to be executed. Is this possible? If so how?
(I already tried calling virtual methods from python which dispatch the actual call to a C++ method, but that does not match my requirements)
Yes, you need to enable the SWIG "directors" feature for the class Base containing the virtual method. You can read about it in the documentation here.
The documentation will tell you that you need to add two things to the SWIG interface file:
At the very beginning, edit the %module directive to enable the use of directors at all:
%module(directors="1") your_modulename
Before the declaration of the class Base or the corresponding %include directive, put the following to enable the directors feature for that class:
%feature("director") Base;

Registering derived classes with reflection, good or evil?

As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.
My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism? That way, the list gets populated dynamically as we add new types.
Here is an example. Please no comment about how loading images can be done other ways, we know.
Suppose we have the following IImageFileFormat interface:
public interface IImageFileFormat
{
string[] SupportedFormats { get; };
Image Load(string fileName);
void Save(Image image, string fileName);
}
Different classes will implement this interface:
[FileFormat]
public class BmpFileFormat : IImageFileFormat { ... }
[FileFormat]
public class JpegFileFormat : IImageFileFormat { ... }
When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.
class ImageLoader
{
public Image Load(string fileName)
{
return FindFormat(fileName).Load(fileName);
}
public void Save(Image image, string fileName)
{
FindFormat(fileName).Save(image, fileName);
}
IImageFileFormat FindFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
return formats.First(f => f.SupportedExtensions.Contains(extension));
}
private List<IImageFileFormat> formats;
}
I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.
By hand:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
formats.Add(new BmpFileFormat());
formats.Add(new JpegFileFormat());
}
By reflection:
public ImageLoader()
{
formats = new List<IImageFileFormat>();
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length > 0)
{
formats.Add(Activator.CreateInstance(type))
}
}
}
I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.
Please discuss.
My personal preference is neither - when there is a mapping of classes to some arbitrary string, a configuration file is the place to do it IMHO. This way, you never need to modify the code - especially if you use a dynamic loading mechanism to add new dynamic libraries.
In general, I always prefer some method that allows me to write code once as much as possible - both your methods require altering already-written/built/deployed code (since your reflection route makes no provision for adding file format loaders in new DLLs).
Edit by Coincoin:
Reflection approach could be effectively combined with configuration files to locate the implmentations to be injected.
The type could be declared explicitely in the config file using canonical names, similar to MSBuild <UsingTask>
The config could locate the assemblies, but then we have to inject all matching types, ala Microsoft Visual Studio Packages.
Any other mechanism to match a value or set of condition to the needed type.
My vote is that the reflection method is nicer. With that method, adding a new file format only modifies one part of the code - the place where you define the class to handle the file format. Without reflection, you'll have to remember to modify the other class, the ImageLoader, as well
Isn't this pretty much what the Dependency Injection pattern is all about?
If you can isolate the dependencies then the mechanics will almost certainly be reflection based, but it will be configuration file driven so the messiness of the reflection can be pretty well encapsulated and isolated.
I believe with DI you simply say I need an object of type <interface> with some other parameters, and the DI system returns an object to you that satisfies your conditions.
This goes together with IoC (Inversion of Control) where the object being supplied may need something else, so that other thing is automatically created and installed into your object (being created by DI) before it's returned to the user.
I know this borders on the "no comment about loading images other ways", but why not just flip your dependencies -- rather than have ImageLoader depend on ImageFileFormats, have each IImageFileFormat depend on an ImageLoader? You'll gain a few things out of this:
Each time you add a new IImageFileFormat, you won't need to make any changes anywhere else (and you won't have to use reflection, either)
If you take it one step further and abstract ImageLoader, you can mock it in Unit Tests, making testing the concrete implementations of each IImageFileFormat that much easier
In vb.net, if all the image loaders will be in the same assembly, one could use partial classes and events to achieve the desired effect (have a class whose purpose is to fire an event when the image loaders should register themselves; each file containing image loaders can have use a "partial class" to add another event handler to that class); C# doesn't have a direct equivalent to vb.net's WithEvents syntax, but I suspect partial classes are a limited mechanism for achieving the same thing.