我正在将一个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.MarshallDirectiveException:";参数#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);