将C DLL导入C#控制台应用程序时,如何编组结构参数byRef?

问题描述

我正在将C DLL导入我的C#程序,并且必须编组ByRef结构参数。

这是C中函数的签名:

extern "C" {
int __stdcall FuncToImport(const char* stringToMarshall,StructFromDLL* structToMarshall);
...
...
...
}

这是我尝试在C#中导入它的方式

[DllImport("ImportedDll.dll",CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr FuncToImport(string stringToImport,ref HandleRef structToImport);

在Main中调用函数时,出现异常: System.Runtime.InteropServices.MarshalDirectiveException:无法编组“参数7”:HandleRefs不能编组为ByRef或不是托管/托管参数。。”

正确编组参数的一种可行方法是什么?

解决方法

尝试一下

[DllImport("ImportedDll.dll",CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr FuncToImport(string stringToImport,IntPtr structToImport);

private static IntPtr StructToPointer<T>(T Struct) where T : struct
{
    //Allocates the necessary memoryspace and creates a pointer to this memory
    int rawsize = Marshal.SizeOf(Struct);
    IntPtr pointer = Marshal.AllocHGlobal(rawsize);

    //Writes the current data from the struct to the allocated memory
    Marshal.StructureToPtr(Struct,pointer,false);

    return pointer;
}

private static T PointerToStruct<T>(IntPtr pointer) where T : struct
{
    //Creates a Struct of the type of T from the pointed memory
    T Struct = Marshal.PtrToStructure<T>(pointer);
    //Frees the allocated memory
    Marshal.FreeHGlobal(pointer);
    return Struct;
}

IntPtr pointer = StructToPointer(structToImport);

FuncToImport("",pointer);

structToImport = PointerToStruct<Type of structToImport>(pointer);