views:

229

answers:

3

I'm working with some COM objects in C#, one of them has a function called SetLogFile that takes an IntPtr. How can I create the file in C# then pass it as an IntPtr to that COM function?

EDIT: The function requires an open file handle: http://msdn.microsoft.com/en-us/library/aa915939.aspx

+4  A: 

You're a little vague as to what you have to pass in as the "file"- if you have a FileStream you can hand in FileStream.Handle as the IntPtr (assuming its expecting a HANDLE value)

See "How to pass parameters of Type HANDLE from C# to C++ DLL".

Ruddy
+2  A: 

This is heavily dependent on exactly what the SetLogFile method is expecting to receive for the IntPtr parameter. If its expecting a COM object and the C# method implements the appropriate interface you can use the following to pass the variable.

var ptr = Marshal.GetIUnknownForObject(theParameter);
try {
  theComObject.SetLogFile(ptr);
} finally {
  Marshal.Release(ptr);
}

If it's expecting an actual Win32 handle. You'll need to go through the file system API to obtain the handle to the file and then pass it into the method.

JaredPar
A: 

You could probably use the SafeFileHandle property of a FileStream object. I'm not sure about the ramifications of doing that, though, so it might be safer to P/Invoke CreateFile.

Luke