Passing LPVOID between managed to unmanaged code

G

Guest

Hi,
I would like to pass-in the structure (typedef) from the C# to managed C++ and eventually to the unmanaged C++ DLL. Unmanaged C++ DLL expects the LPVOID as a parameter for passing the structure. Unamaned C++ DLL fills-in data into memebers of the structure. To accomplish this, I am passing IntPtr from C# to managed C++ and then marshalling IntPtr to void* before passing it into the unmanaged C++ DLL. The question I have is how do I cast structure into the IntPtr in my C# code? Is this a feasible option or there is any opther alternative for passing structure as an LPVOID?
-Jon
 
R

Rob Teixeira [MVP]

Create a managed Struct in C# that has the same look as the C++ typedef.
You can completely bypass MC++ and use P/Invoke to call the unmanaged DLL
function directly (using the DLLImport attribute in C#). When you do this,
you can bypass all the casting by making the unmanaged function prototype
parameter in C# a ref or out parameter. Alternately, you can use an Unsafe
context specifier and make the parameter myStruct* (pointer to whatever
struct name you created in C#), and use the & operator in C# to pass the
address. Neither of these two options require IntPtr.

However, if you want to continue what you are already doing in your code,
you can use the Marshal.StructToPtr() method, which returns an IntPtr
containing the address of the struct variable. Just don't forget to pin the
structure with a GCHandle if it wasn't stack allocated.

-Rob Teixeira [MVP]

jon free said:
Hi,
I would like to pass-in the structure (typedef) from the C# to managed C++
and eventually to the unmanaged C++ DLL. Unmanaged C++ DLL expects the
LPVOID as a parameter for passing the structure. Unamaned C++ DLL fills-in
data into memebers of the structure. To accomplish this, I am passing IntPtr
from C# to managed C++ and then marshalling IntPtr to void* before passing
it into the unmanaged C++ DLL. The question I have is how do I cast
structure into the IntPtr in my C# code? Is this a feasible option or there
is any opther alternative for passing structure as an LPVOID?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top