How to call to COM method with IntPtr pointers

0

I have some DLLs without source code, which are written in C++(COM). I can import these into my C# Solution and can use the given classes and methods. Some of the parameters of these methods are of type IntPtr, which results from the typelib import. I do know the acutal type of struct I need a pointer to. This struct is sometimes managed, so I can not simply create a pointer to it.

For example a method like this:

void ListExtensions(out int pCount, System.IntPtr pExtensions)

The pExtension must be a pointer to an array of structs called "ExtensionId" which is in another COM DLL. The struct looks like this:

public struct ExtensionId
{
    public ExtensionGuid data;
}

public struct ExtensionGuid
{
    public int Data1;
    public short Data2;
    public short Data3;
    public byte[] Data4;
}

How do I create an pointer to an array of ExtensionId? I tried something like this

ExtensionId *ids = new ExtensionId[10];

but Visual Studio does say "Type ExtensionId[] cannot by cast to ExtensionId*"

I also tried this

ExtensionId[] ids = new ExtensionId[10];
GCHandle handle = GCHandle.Alloc(ids);
IntPtr ptr = (IntPtr)handle;
int pCount;
ListExtensions(out pCount, ptr);
ExtensionId[] result = (ExtensionId[])handle.Target;

but in the last line of code the programm crashes with the following error:

The runtime has encountered a fatal error. The address of the error was at 0x73d87e37, on thread 0x5f8. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

Can anyone give some advice how to call a method like this properly?

Thanks in advance

c#
pointers
interop
asked on Stack Overflow Apr 25, 2019 by User81772

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0