English 中文(简体)
Getting a byte array from out of process C++ COM to C#
原标题:

What s the best way to get a chunk of memory (i.e. void*) from a COM server to C#?

We have been using an IStream (using CreateStreamOnHGlobal) and passing that back, which worked. However when we tried this on x64 CLR with x32 C++ COM it blows up.

The COM has to be x32 because it uses external 32 bit DLLs. The C# could be forced to run 32 bit but the challenge is to keep that running as x64.

最佳回答

Answering my own question.

When you return an IStream from your own COM server the .NET interop DLL puts an IStream into it s interface. For example lets say the type library is MyComServer, then the interop will contain a class MyComServer.Interop.IStream.

this IStream class has functions like RemoteRead, RemoteWrite etc. These take a ref byte as the first parameter. Using these worked fine on 32bit to 32bit, but that ref probably becomes a pointer and so on 64 to 32 something went wrong.

The solution is to convert the MyComServer.Interop.IStream to System.Runtime.InteropServices.ComTypes.IStream using "as" (or just cast probably). This then takes a more familiar byte[], int count and IntPtr for the return size.

The IntPtr is annoying as it could be an out int, but I used (typing this in by hand so not compiler checked..)

byte[] buffer = new byte[100];
IntPtr ptr = Marshall.AllocHGlobal( sizeof(int) );
stream.Read( buffer, 100, ptr );
问题回答

If you have .NET 3.5, have a look at System.IO.Pipes- create a well-known pipe name and squirt it over from unmanaged code with the Win32 named pipes APIs.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签