【问题标题】:Calling C Pointers in vb.net在 vb.net 中调用 C 指针
【发布时间】:2014-11-18 18:26:39
【问题描述】:

我是新来的,如果我没有使用正确的术语,请原谅我。我有一个 c 编译的 dll,我从 vb 2013 调用它。我遇到的问题是调用 c dll 中的指针。我尽了最大努力并设法从 int * 中读取,但是 u_int * 或 float * 怎么样?以下是我目前编写的代码。

我的.dll:

BCAPDLL_API int * __stdcall myfunc1(int * localPtr){
localPtr[0] = 100;
localPtr[1] = 200;
localPtr[2] = 300;
localPtr[3] = 400;
return localPtr;
}

BCAPDLL_API u_int * __stdcall myfunc2(u_int * localPtr){
localPtr[0] = 100;
localPtr[1] = 200;
localPtr[2] = 300;
localPtr[3] = 400;
return localPtr;
}

BCAPDLL_API float * __stdcall myfunc3(float * localPtr){
localPtr[0] = 100;
localPtr[1] = 200;
localPtr[2] = 300;
localPtr[3] = 400;
return localPtr;
}

在 vb.net 中:

    Sub Main()

    Dim mycomm(4) As Integer
    Dim localPtr As IntPtr = Marshal.AllocHGlobal(4)
    Dim ptr As IntPtr = testFunc(localPtr)
    Marshal.Copy(ptr, mycomm, 0, 4)

    For i As Integer = 0 To 3
        MsgBox(Marshal.ReadInt32(mycomm, i * Marshal.SizeOf(GetType(Int32))))
    Next i
    Marshal.FreeHGlobal(localPtr)

    End Sub

这个函数让我从 dll 中获取函数 int * 的所有值,但是对于 u_int * 和 float *,我不能使用与 Marshal 类不支持 UIntPtr 相同的方法; vb.net 中不存在 FloatPtr。我该怎么做?提前致谢。

【问题讨论】:

  • 现在切换到 C#(支持指针)是否为时已晚?
  • 这是否意味着它在 vb.net 中是不可能的?我是否必须仅仅因为 u_int * 和 float * 而学习 C#?
  • 如果我错了,请原谅,但你不是只是得到一个指向内存中值的指针吗?您应该能够将IntPtrMarshal.Copy 的数据保存到byte[] 中,并使用BitConverter.ToSingle(myCopiedBytes, 0) 获得float 的实际值。
  • 你能提供一些代码示例吗?
  • 谢谢泰科布!!!终于搞定了!!!

标签: c vb.net pointers dll


【解决方案1】:
    Dim oSize As Integer = 4
    Dim mycomm(oSize) As Byte
    Dim localPtr As IntPtr
    Dim ptr As IntPtr = testFunc3(localPtr)

    For i = 0 To oSize - 1
        Marshal.Copy(ptr, mycomm, 0, oSize)
        MsgBox(BitConverter.ToSingle(mycomm, 0))
        ptr = IntPtr.Add(ptr, Marshal.SizeOf(GetType(Single)))
    Next i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多