|
From: Peter G. <pet...@fa...> - 2010-04-14 15:23:55
|
Hello All,
I have a CPP method signature say:
string fun();
where the string contains binary data, nulls etc and I want to generate a C#
method:
byte[] fun();
Has anyone solved this problem or similar?
However, I look at this it seems I need to return an address and a length
from CPP to C#. There appears to be a choice when to copy from the unmanaged
pointer to managed memory. This can be either in the CPP or C# code,
perhap???
I have something that works (In a simple example). I do not think this
solution is good. At the very least there is contention because of a global
lock (see below %typemap(csout) FSD_RBSTRING ). I cannot take credit for
this solution as I found it on the web(date 2005) and just tweaked it.
Here is what I have so far:
regards
_________________________
%typemap(ctype) FSD_RBSTRING %{void%}
%typemap(imtype) FSD_RBSTRING %{void%}
%typemap(cstype) FSD_RBSTRING %{byte[]%}
%typemap(out) FSD_RBSTRING
%{ SWIG_csharp_bytearray_callback((const unsigned char *)$1->data(),
(int)$1->size()); %}
%typemap(csout) FSD_RBSTRING {
lock($modulePINVOKE.byteArrayHelper) {
$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=%{
internal 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_$module(SWIGByteArrayDelegate
byteArrayDelegate);
static void CreateByteArray(IntPtr data, int size)
{
arraybuffer = new byte[size];
Marshal.Copy(data, arraybuffer, 0, size);
}
static SWIGByteArrayHelper()
{
SWIGRegisterByteArrayCallback_$module(byteArrayDelegate);
}
}
public static SWIGByteArrayHelper byteArrayHelper = new
SWIGByteArrayHelper();
private static byte[] arraybuffer = null;
internal static byte[] GetBytes() { byte[] b = arraybuffer; arraybuffer =
null; return b;}
%}
%insert(runtime) %{
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL
SWIGRegisterByteArrayCallback_$module(SWIG_CSharpByteArrayHelperCallback
callback) {
SWIG_csharp_bytearray_callback = callback; } %}
_________________________
--
View this message in context: http://old.nabble.com/Want-to-generate-C--byte---fun%28%29-from-CPP-string-fun%28%29-tp28244141p28244141.html
Sent from the swig-user mailing list archive at Nabble.com.
|