【问题标题】:VB.NET passing array of strings to a C functionVB.NET 将字符串数组传递给 C 函数
【发布时间】:2013-06-27 13:04:16
【问题描述】:

想知道如何使用VB.NET调用以数组为参数的C++函数:

dim mystring as string  = "a,b,c"
dim myarray() as string
myarray = split(mystring,",")
cfunction(myarray)

cfuncton 会在 C++ 中,但是由于其他原因我不能在 C++ 中使用字符串变量类型,我只能使用 char。为了正确接收数组并将其拆分回字符串,我的 C++ 函数应该是什么样子?

【问题讨论】:

  • 我在这个例子中使用 C++
  • 请贴出C++方法的声明,这样可以帮助其他人识别错误

标签: c++ arrays vb.net


【解决方案1】:

基本上,创建一些固定内存来存储字符串,并将其传递给您的函数:

Marshal.AllocHGlobal 将为您分配一些内存,您可以将这些内存分配给您的 c++ 函数。见http://msdn.microsoft.com/en-us/library/s69bkh17.aspx。您的 c++ 函数可以接受它作为 char * 参数。

例子:

首先,您需要将字符串转换为一个大字节[],用空值 (0x00) 分隔每个字符串。让我们通过只分配一个字节数组来有效地做到这一点。

Dim strings() As String = New String() {"Hello", "World"}
Dim finalSize As Integer = 0
Dim i As Integer = 0
Do While (i < strings.Length)
    finalSize = (finalSize + System.Text.Encoding.ASCII.GetByteCount(strings(i)))
    finalSize = (finalSize + 1)
    i = (i + 1)
Loop
Dim allocation() As Byte = New Byte((finalSize) - 1) {}
Dim j As Integer = 0
Dim i As Integer = 0
Do While (i < strings.Length)
    j = (j + System.Text.Encoding.ASCII.GetBytes(strings(i), 0, strings(i).Length, allocation, j))
    allocation(j) = 0
    j = (j + 1)
    i = (i + 1)
Loop

现在,我们只需将其传递给我们使用 Marshal.AllocHGlobal 分配的一些内存

Dim pointer As IntPtr = Marshal.AllocHGlobal(finalSize)
Marshal.Copy(allocation, 0, pointer, allocation.Length)

在这里调用你的函数。你还需要传递你给函数的字符串数量。完成后,记得释放分配的内存:

Marshal.FreeHGlobal(pointer)

HTH。

(我不知道 VB,但我知道 C# 以及如何使用 Google (http://www.carlosag.net/tools/codetranslator/),如果有点离题,请见谅!:P)

【讨论】:

    【解决方案2】:

    这个C#的例子和VB.NET一样,有C++方法的声明,如果你想要的话,你可以使用它。 C#: passing array of strings to a C++ DLL

    【讨论】:

      猜你喜欢
      • 2015-09-09
      • 1970-01-01
      • 2017-04-05
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      相关资源
      最近更新 更多