c++ - vb.net byte[] 到 C++ char*

标签 c++ vb.net interop marshalling

我正在调用一个需要 char* 作为其参数之一的非托管 C++ dll,我想将一个 byte[] 插入其中。该项目是用 VB.NET 编写的。

哪种类型的编码适用于此?

最佳答案

如果您需要固定托管结构以便将其作为参数传递,您可以使用以下代码。

    // (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);

关于c++ - vb.net byte[] 到 C++ char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/264318/

相关文章:

c++ - 支持优先级、更新、推送和弹出的最佳数据结构是什么

c++ - Windows 编辑启动应用程序/C++

c++ - CUDA 中的并行批处理小矩阵不适用于 for 循环

C++20 从带括号的值列表初始化聚合,不支持内部数组

javascript - 我应该在 vb.net 上做什么来显示我的模式弹出窗口

java - Clojure,Java interop : how to get File. 分隔符?

c# - 如何使用c#/VB.NET在word中插入书签

sql-server - VBNET中应使用什么错误处理

java - 从 Java 调用 Scala 代码?

c# - 编码 C# 枚举数组以在 C++ 代码中修改