VB.NET将字符串数组传递给C函数
VB.NET passing array of strings to a C function
想知道如何使用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
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中