passing struct to unmanaged code

  • Thread starter Thread starter adrin
  • Start date Start date
A

adrin

hi i have the following problem:
i use functions from an external dll(normal w32 unmanaged library) which
takes a structure address as an argument..
how do i pass it in c#?
i tried using array instead od struct and fixed statement to get a pointer,
it seemed to work, but i bet there is a better and more elegant way to do
that

and a second issue which is more imprortant :)
one member of the structure given as an argument(or rather address of which
is given as an arg) is a pointer to a callback function... how do i get
function pointer in c# and pass it to that unmanaged code, so it can be
called from that code in the future?
please help me, i would be very grateful.
 
i use functions from an external dll(normal w32 unmanaged library) which
takes a structure address as an argument..
how do i pass it in c#?

Make it a ref parameter, that works in most cases.

one member of the structure given as an argument(or rather address of which
is given as an arg) is a pointer to a callback function... how do i get
function pointer in c# and pass it to that unmanaged code, so it can be
called from that code in the future?

Declare it as a delegate type with the right callback signature, and
the CLR will marshal it to a function pointer for you.



Mattias
 
There is a section in MSDN on P/Invoke:

http://msdn.microsoft.com/library/d...en-us/cpguide/html/cpconpassingstructures.asp

and an article how to pass structure:
http://msdn.microsoft.com/library/d...en-us/cpguide/html/cpconpassingstructures.asp

A good idea is to look at Interop Marshalling for specific data types
marshalling, for instance strings in different cases. Have a look at the
following:

http://msdn.microsoft.com/library/d...cpguide/html/cpconplatforminvokedatatypes.asp

http://msdn.microsoft.com/library/d...cpguide/html/cpconplatforminvokedatatypes.asp

You should be most happy with:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstructssample.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconosinfosample.asp

Articles are not long, and samples are very clear and meaningful. Worth
browsing and looking for an adequate sample you need.
 
Declare it as a delegate type with the right callback signature, and
the CLR will marshal it to a function pointer for you.
sorry, but what do you mean by right callback signature :)?
 
sorry, but what do you mean by right callback signature :)?

Just that you have to get the parameter types (and in/out-ness) right,
just like you have for the DllImport function itself.



Mattias
 
Back
Top