C# Marshaling and automation

PingSpike

Lifer
Feb 25, 2004
21,754
599
126
I don't know a lot about marshaling or automation, still reading and learning I guess.

I have a C++ MFC application that exposes a method that takes a variant* as a parameter. The variant* is then assigned to point to a safearray of strings. I've used some code in a C++ application from another developer that I mostly to understand. It just allocates a block of memory of sizeof VARIANT and assigns it to a LPVARIANT. Once it is passed it gets the parray and the strings can be copied out.

I've even gotten it working in C# but I don't entirely understand how marshaling works. In C# the method is exposed and calls for the a ref object instead of an LPVARIANT, which makes sense as the LPVARIANT doesn't exist as a managed type and I guess ref object is the closet you're going to get.

This MarshalAs attribute allows the string array to be used to get the desired values. I have to cast to object first of course before using it.

[MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] string[] pvParameterToPass;

The thing I don't like about this is the MarshalAs attribute only seems to work on class members. I don't need this available to the whole class, I only need it for the scope of a method. Is there a different way to do this? The Marshal classes' methods don't really seem to offer exactly what I want.

Again, I'm kind of just fumbling with this. I think I need to do some reading on marshaling and automation.
 

Blieb

Diamond Member
Apr 17, 2000
3,475
0
76
This is C# interop (interoperability).

You have to declare the method/signature somewhere in your class. I assume this is for considerations made at runtime.

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx
Marshalling "provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code."
 

hans007

Lifer
Feb 1, 2000
20,212
18
81
i dont know anything about marshalling but i don't think it matters that you used a variant.

i know if you used COM with variants you could access COM From C# but that doesn't seem to be what you are doing. from what definition of what marshalling is from blieb it sounds like you do have to make signatures to basically cast your C++ functions to c# ones ( I know you can do this in java with JNI... so i could see why they would have something like this in c# as well)