SWIG typemap for C# to receive gdBuffer as byte array

Szekeres Tamás szekeres.tamas at FREEMAIL.HU
Tue Jun 21 17:30:41 EDT 2005


Mapserver 4.6 implements imageObj.getBytes() to get the image as array of
bytes. To generate C# wrapper a proper typemap should be created for this
language. The folowing code gives a solution, if you have a better one
please reply:

create a file eg. csmodule.i with the following contents:


%typemap(ctype) gdBuffer %{void%}
%typemap(imtype) gdBuffer %{void%}
%typemap(cstype) gdBuffer %{byte[]%}
%typemap(out) gdBuffer
%{ SWIG_csharp_bytearray_callback($1.data, $1.size);
gdFree($1.data); %}
%typemap(csout) gdBuffer {
$imcall;
return $modulePINVOKE.GetBytes();
}

%insert(runtime) %{
/* Callback for returning byte arrays to C#, the resulting array is not
marshaled back, so the caller should call GetBytes to get back the results
*/
typedef void (SWIGSTDCALL* SWIG_CSharpByteArrayHelperCallback)(const
unsigned char *, const int);
static SWIG_CSharpByteArrayHelperCallback SWIG_csharp_bytearray_callback =
NULL;
%}
%pragma(csharp) imclasscode=%{
class SWIGByteArrayHelper
{
public delegate void SWIGByteArrayDelegate(IntPtr data, int size);
static SWIGByteArrayDelegate bytearrayDelegate = new
SWIGByteArrayDelegate(CreateByteArray);
[DllImport("$dllimport",
EntryPoint="SWIGRegisterByteArrayCallback_$module")]
public static extern void
SWIGRegisterByteArrayCallback_mapscript(SWIGByteArrayDelegate
bytearrayDelegate);
static void CreateByteArray(IntPtr data, int size)
{
arraybuffer = new byte[size];
Marshal.Copy(data, arraybuffer, 0, size);
}
static SWIGByteArrayHelper()
{
SWIGRegisterByteArrayCallback_$module(bytearrayDelegate);
}
}
static SWIGByteArrayHelper bytearrayHelper = new SWIGByteArrayHelper();
static byte[] arraybuffer;
internal static byte[] GetBytes()
{
return arraybuffer;
}
%}
%insert(runtime) %{
#ifdef __cplusplus
extern "C"
#endif
DllExport void SWIGSTDCALL
SWIGRegisterByteArrayCallback_$module(SWIG_CSharpByteArrayHelperCallback
callback) {
SWIG_csharp_bytearray_callback = callback;
}
%}


modify mapscript.i as

/* C# */
#ifdef SWIGCSHARP
%include "csmodule.i"
#endif


the method can be accessed as the following code in c#:

using(imageObj image = map.draw())
{
byte[] img = image.getBytes();
using (MemoryStream ms = new MemoryStream(img))
{
    mapPicture.Image = Image.FromStream(ms);
}
}



Tamas Szekeres



More information about the mapserver-users mailing list