I have swig.i file like that:
%module ogr_api
%{
#include "ogr_api.h"
%}
%inline %{
typedef void *OGRSFDriverH;
%}
/* OGRSFDriverRegistrar */
OGRDataSourceH OGROpen( const char *, int, OGRSFDriverH * )`
and I get the following .c wrapper:
...
SWIGEXPORT void * D_OGROpen(char * jarg1, int jarg2, void * jarg3) {
...
That is SWIG translates OGRSFDriverH to just void*. I need to save the type name. How could I do it?
Also I loss const in the first argument, but this is the next question.
Assuming I’ve understood your question correctly you have a number of opaque “handles” that in C are really
typedefs tovoid*, but in your generated interface you want to enforce stronger type checking. (Note that the default behaviour is correct here in that it permits usage that exactly mirrors C). You want to prevent a handle of one sort accidentally being given to a function that takes a “different”void*, i.e. expose thetypedefas a sort of strong typedef.You can do that with SWIG without too much trouble. The key thing to remember is that the interface file you give SWIG doesn’t always have to exactly match the real C types, so long as the code that gets produced at the end is correct and legal still.
I put together an example to illustrate this. Given a header file, which is presumably similar in principle to your ogr_api.h:
You want to only be able to call
foowith aHandleType1andbarwith aHandleType2.I used the following interface to get such behaviour:
The code that gets generated by this is perfectly fine though since it doesn’t try to do anything that can’t be done with
void*and they’re both handled as just pointers in the wrapper.The
%nodefaultctoris needed to prevent SWIG from trying to construct a new handle based on the lies we told it, you’d get a compiler error with out this. (You probably want to suppress the destructor too, or customise it since that will be callingfree).Which generates a Java interface that only allows the correct handle to be used for each function. I tested this with:
It’s a bit of a trick, but it works, have a look at the wrapper that gets generated to convince yourself.
Which compiled and ran as expected. The commented out lines give errors as you’d hope.
For a D specific solution, where I understand
typedefgives a strong typedef (unlikealiaswhich is more liketypedefin C) I think you can use something like:To generate the interface you want. The typemaps modify what the types used in the D interface are, the
%pragmainserts thetypedefinto the (proxy) part of the generated interface.