DLL调用和结构转换 [英] DLL call and structure conversion
本文介绍了DLL调用和结构转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
调用导入的DLL函数所需的帮助
Help needed in calling imported DLL function
[DllImport("ABC.DLL")
public static extern uint Func(IntPtr pOutput, IntPtr pNum);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct MyStruct
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
public byte[] ID;
[MarshalAs(UnmanagedType.LPStr)]
public string Path;
public IntPtr AnotherStruct;
...
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct AnotherStruct
{
public ushort FormatType;
public ushort FormatIndex;
}
// calling imported function...
MyStruct Arr=new MyStruct[16];
AnotherStruct FormatArr=new AnotherStruct[16];
IntPtr pArr=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MyStruct))*16);
for(int i=0; i<16; i++) // allocate memory for AnotherStruct
Arr[i].AnotherSruct=Marshal.AllocHGlobal(Marshal.Sizeof(AnotherStruct[i]));
int iCount=0; IntPtr pCount=new IntPtr(iCount);
if(Func(out pArr, out pCount)!=0) return false;
return true;
}
Func()返回true,但pArr内容保持不变.
我在结构转换或内存分配上做错了吗?
感谢您的任何建议.
C ++代码如下...
Func() return true, but the pArr contents remain intact.
Did I do wrong in the structure conversion or memory allocation?
Thanks for any suggestions.
The C++ codes is as follow...
Func(MyStruct** pStruct, unsigned int* pNum);
struct MyStruct
{
unsigned char ID[16];
unsigned int* pPath;
AnotherStruct* pFormat;
}
struct AnotherStruct
{
unsigned int FormatType;
unsigned int FormatIndex;
}
推荐答案
您不能在C#中直接使用指针符号.如果要返回指针,则以 System.IntPtr 类型捕获地址.
遵循的步骤
1.首先,使用Marshal.AllocHGlobal()在非托管区域中分配一个内存,以从托管代码中复制结构.
2.使用Marshal.Copy()复制结构.
请参考MSDN上的一些示例,或者看看 .NET Interop Revisited. [ ^ ]
You can not directly use pointer notation in C#. If you are returning a pointer then catch the address in System.IntPtr type.
Steps to Follow
1. First allocate a memory in unmanaged area to copy the structure from managed code, using Marshal.AllocHGlobal().
2. Copy the structure using Marshal.Copy().
Refer some examples on MSDN or else have a look at .NET Interop Revisited.[^]
这篇关于DLL调用和结构转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文