views:

373

answers:

3

Hi,

I am new to C# and visual studio. I have a C# GUI that passes parameters to functions exported from a C++ DLL. The platform in Visual Studio 2005.

I have a function in the c++ DLL that take parameters of the following types: UINT8 UINT16 LPCWSTR someword (the following has been defined in the c+= dll : typedef void* someword..so basically someword is just a void pointer.)

Can you please help me how do i pass parameters from my C# GUI to this function imported from the DLL. I know it has to be done using MarshalAs but i donno how. also the c++ dll is unmanaged. Any help would be apreciated.

Thanks, Viren

A: 

Try something like this:

[DllImport("lib.dll")]
public static extern int FunctionName(IntPtr somevariable, ushort var1, byte var2, byte var3, byte var4, [MarshalAs(UnmanagedType.LPWStr), In] string str1, [MarshalAs(UnmanagedType.LPWStr), In] string str2);
Ravadre
thanks..btw i am importing the dll using the following statement:[DllImport("lib.dll", CharSet = CharSet.Ansi)]so is the 'charset' going to make a difference to what you suggested earlier??
VP
I think it should work properly if you will explicitly tell how to marshal each string, but I'd check just to make sure and start worrying if it's not :).
Ravadre
IntPtr works fine..thanks a lot.
VP
+1  A: 

Could you help us out by providing the signature of the C++ DLL? For the types you specified, here are the correct types

  • UINT8: UInt8
  • UINT16: UInt16
  • LPCWSTR: String (make sure to use the [In] Marshal attribute on the parameter as well)

Have you checked out the PInvoke Interop Assistant yet? It was designed to help people through these scenarios by converting C++ signatures into the equivalent DLL import

JaredPar
thanks JaredPar for the link..I used byte, ushort and string for the types respectively and it works fine..
VP
byte is just a shorcut for System.UInt8, ushort - for System.UInt16, and string for System.String, so you are closer to JaredPar's solution that you think ;-).
Ravadre
A: 

Hi everyone. Thanks for all your answers to previous question. Now I gotta pass an InParameter from my C# application to an exported function from a VC++ DLL. The function accepts 2 parameters :

int func_name (FILE* fp, BYTE& by);

fp is In and by is Out parameter.

I was thinking of marshaling using IntPtr for the FILE* and using byte for BYTE. Is it correct? If I write the following in C#

[DllImport("name_of_project.dll", CharSet = CharSet.Ansi)] public static extern int func_name(IntPtr FilePointer, [MarshalAs(UnmanagedType.BYTE&)] byte by);

will it work? I think it will give an error for the '&' sign in the marshaling statement. How do I pass the out parameter by reference?

Your help would be much appreciated.

Thanks,Viren

VP