想知道如何使用VB.NET调用C++函数以与阵列作为一个参数:VB.NET传递字符串的数组到C函数
dim mystring as string = "a,b,c"
dim myarray() as string
myarray = split(mystring,",")
cfunction(myarray)
的cfuncton将在C++中,但我不能由于其他原因在C++中使用字符串变量类型,我只能使用char。我的C++函数应该如何才能正确接收数组并将其分割回其字符串?
想知道如何使用VB.NET调用C++函数以与阵列作为一个参数: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 *参数。
例子:
首先,您需要将您的字符串转换为一个大的byte [],分隔每个字符串以空值(0×00)。让我们通过分配一个字节数组来高效地完成这个任务。现在
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#: passing array of strings to a C++ DLL
C++/CLR?....... –
本例中使用C++ – user2527738
请张贴C++方法的声明,这可以帮助其他人识别错误 – ahmedsafan86