VB.NET将字符串数组传递给C函数

VB.NET passing array of strings to a C function

本文关键字:函数 数组 NET 字符串 VB      更新时间:2023-10-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++函数应该是什么样子才能正确接收数组并将其拆分为字符串?

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

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

示例:

首先,您需要将字符串转换为一个大字节[],用null(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#和如何使用谷歌(http://www.carlosag.net/tools/codetranslator/),如果有点不对劲,很抱歉!:P)

C#中的这个例子与VB.NET相同,它有C++方法的声明,如果这是你想要的,你可以使用它。C#:将字符串数组传递到C++DLL