我正在调用一个非托管C++ dll,该dll需要一个char*作为其参数之一,并且我想将一个byte[]推入其中。该项目是用VB.NET编写的。
哪种类型的编组可以解决这个问题?
发布于 2008-11-05 08:25:57
如果需要固定托管结构以将其作为参数传递,则可以使用以下代码。
// (c) 2007 Marc Clifton
/// <summary>
/// A helper class for pinning a managed structure so that it is suitable for
/// unmanaged calls. A pinned object will not be collected and will not be moved
/// by the GC until explicitly freed.
/// </summary>
internal class PinnedObject<T> : IDisposable where T : struct
{
protected T managedObject;
protected GCHandle handle;
protected IntPtr ptr;
protected bool disposed;
public T ManangedObject
{
get
{
return (T)handle.Target;
}
set
{
Marshal.StructureToPtr(value, ptr, false);
}
}
public IntPtr Pointer
{
get { return ptr; }
}
public int Size
{
get { return Marshal.SizeOf(managedObject); }
}
public PinnedObject()
{
managedObject = new T();
handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);
ptr = handle.AddrOfPinnedObject();
}
~PinnedObject()
{
Dispose();
}
public void Dispose()
{
if (!disposed)
{
if (handle.IsAllocated)
handle.Free();
ptr = IntPtr.Zero;
disposed = true;
}
}
}
}然后,您可以使用PinnedObject.Pointer调用非托管代码。在外部声明中,使用IntPtr作为该参数的类型。
PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();
pinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;
Unmanaged.Method(pinBatteryQueryInfo.Pointer);发布于 2009-11-21 21:52:49
在您的PInvoke定义中,只需将char*参数声明为byte[],标准编组程序就会处理这些工作。
但这可能是也可能不是最好的主意。C++函数期望的是字符串还是数据缓冲区(C/C++代码通常使用char*作为缓冲区,这取决于char是一个字节的事实)?
如果它是一个缓冲区,那么byte[]当然是正确的,但是如果它需要字符串,那么如果将参数声明为字符串(显式)并使用Encoding.ASCII.GetString()将byte[]转换为字符串,可能会更清楚。
此外,如果C++函数需要一个字符串,并且您决定将该参数声明为byte[],请确保字节数组以零结束,因为这是C/C++确定字符串结尾的方式。
https://stackoverflow.com/questions/264318
复制相似问题