【问题标题】:How to import a C++ function with int** and double** parameters如何使用 int** 和 double** 参数导入 C++ 函数
【发布时间】:2013-11-26 15:49:56
【问题描述】:

我正在尝试在我的 C# 代码中导入一个 c++ 函数。

这个函数定义为:

int SetPointers(int* ID, int* BufferID, int** Pointer, double** Time, int NumberOfPointers);

ID 为 int 数组, BufferId 一个 int 数组, 指向一个int数组, 为双精度数组计时,
NumberOfPointers 一个整数。

我尝试使用 IntPtr 没有成功。

这是我尝试过的最新代码:

[DllImport("open.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
    public unsafe static extern int SetPointers(int* ID, int* BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);
    public unsafe int _SetPointers(int[] ID, int[] BufferID, ref int[] Pointer, ref double[] Time, int NumberOfPointers)
     {
         IntPtr fQueue = IntPtr.Zero;
         IntPtr fTime = IntPtr.Zero;
         int breturn = -1;
         fixed (int* fId = ID)
            fixed (int* fBufferID = BufferID)
                fQueue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Pointer.Length);
                fTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(double)) * Timestamp.Length);
                breturn = SetPointers(fId , fBufferID, ref fQueue, ref fTime, NumberOfPointers);
        return breturn;
    }

你知道怎么做吗?

【问题讨论】:

  • malloc 跟这个问题有什么关系?
  • 你需要展示这个函数是如何在非托管代码中使用的。或者显示功能码。
  • 对不起,我是说元帅
  • 我不能修改那个代码,而且很复杂。基本上,ID、BufferId 和 NumberOfPointers 只能由函数读取,而 Pointer 和 Time 就像返回值一样。这有帮助吗?
  • 我不认为你在做正确的事。双重引用可能是一个输出参数 - 请阅读此stackoverflow.com/questions/6810419/…

标签: c# c++ marshalling dllimport intptr


【解决方案1】:

首先,您可能希望对参数使用 IntPtr 而不是 int[]。 在此之后,我没有尝试过,但是将指针编组到指针上,“ref IntPtr”或“out IntPtr”会起作用。

public unsafe int _SetPointers(IntPtr ID, IntPtr BufferID, ref IntPtr Pointer, ref IntPtr Time, int NumberOfPointers);

也看看这个其他线程:How do I marshall a pointer to a pointer of an array of structures?

【讨论】:

  • 前两个参数可以作为数组使用
猜你喜欢
  • 1970-01-01
  • 2011-05-28
  • 2012-06-26
  • 2022-08-09
  • 2012-10-24
  • 2021-07-26
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
相关资源
最近更新 更多