469,582 Members | 2,200 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,582 developers. It's quick & easy.

Interop - returning a buffer through callback

Udi
Hi all,
I'm having difficulties returning a buffer allocated on a callback
called from a native dll to .NET assembly.
(See pseudo code below in "Foo" func):
The managed assembly (the called back function) needs to allocate the
buffer and return it as an out param to the "C" dll.
When invoking the callback from the C code, passing a valid pointer
with sizeParam=0 cause the application to crash - I can't even enter
the callback scope. However, when passing a NULL ptr (and sizeParam =
0) the function is called correctly.

1) What am I doing wrong here?

in the typedef below - I know I need to declare "buf" of type char * *
in order to allocate it in the called func
but does this cause my problem? I doubt it. and if it is -

2) Is there a way to interop a ptr to ptr automatically, without using
IntPtr, Marshal.AllocCoTaskMem and Marshal.FreeCoTaskMem?

Thanks!
Udi.
C file:
~~~~~

typedef void (*FooCallBack)(char * buf, int * size); //both out params

char globalBuff[10];

void Foo(FooCallBack pFunc)
{
char * p = NULL;
(*pFunc)( p , 0); // --Works OK! pFunc is called OK, I'm entering
pFunc scope

(*pFunc)(globalBuff, 0); // --CRASH! NEVER ENTERS pFunc scope
}

..NET
~~~~~

class FooClass
{
delegate void FooCB([MarshalAs(UnmanagedType.LPArray,
sizeParamIndex=1)] byte [] buff, out int size);

[DllImport("MyDll")]
public static extern Foo([MarshalAs(UnmangedType.FunctionPtr)] FooCB
del);

private FooCB fooCB = new FooCB(CallBackCalled);

public void CallBackCalled( byte[] buff, out int size) //both out
params
{
//need to allocate buffer here and return it to the "C" calling
function
size = 30;
buff = new byte[size] ...
}

public ManagedFoo()
{
//handing over the delegate of the callback
Foo(fooCB) ;
}

Apr 19 '07 #1
0 1511

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Randy | last post: by
3 posts views Thread by DG is a god.... | last post: by
3 posts views Thread by =?Utf-8?B?VG9tIEFsbGVu?= | last post: by
1 post views Thread by Reg | last post: by
70 posts views Thread by junky_fellow | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.