[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework.interop

Question about interop and delegates

Alain Frisch

8/30/2007 5:37:00 PM

Hello,

I've a basic question about .Net interop (pinvoke). I'm new to this
subject, so feel free to RTFM me (preferably with the good values for 'M').

I want to call C# methods from C. The easiest way I've found is to pass
C# delegates to C. (I'm aware that I've to take care that these
delegates will not be GC'ed by the CLR, and that all the C functions and
function pointers must be __stdcall.) The delegates are marshaled as
unmanaged function pointers. Now, I need to know the memory management
convention for calling these function pointers. For the example, let's
assume that I've a C# method

string f(string s);

which has been marshaled into:

char* (*f)(char *s);

The question is: who's responsible for freeing the argument s and the
result? By experimenting, I've inferred that the CLR will not free the
argument and does not assume it will survive after f returns. Similarly,
it seems that the CLR allocates the result string with CoTaskMemAlloc,
and so my C code should copy this string somewhere and then
CoTaskMemFree it. In other words, the caller (my C code) is responsible
for both the argument and the result, but it needs to use the
CoTaskMemFree function to release the result's memory.

Is that correct?

Where could I find this kind of information? I've found many detailed
explanation on how to pass and return things from C# to C, but not the
other way around. Naively, I would have assumed that passing an argument
from C to C# was handled similarly as returning a result from C to C#
(ie: the CLR is responsible for desallocating memory), but it seems
instead that the general rules are:
- the caller "owns" both the argument and the result;
- the result is allocated by CoTaskMemAlloc


Cheers,

Alain Frisch