简体   繁体   English

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

[英]VB.NET passing array of strings to a C function

Wondering how to use VB.NET to call a C++ function with an array as a parameter: 想知道如何使用VB.NET调用以数组为参数的C ++函数:

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

The cfuncton will be in C++, but I cannot use the string variable type in C++ due to other reasons, I can only use char. cfuncton将在C ++中使用,但是由于其他原因,我无法在C ++中使用字符串变量类型,只能使用char。 What should my C++ function look like in order to properly receive the array and split it back to its strings? 为了正确接收数组并将其拆分回字符串,我的C ++函数应该是什么样?

Basically, create some pinned memory to store the strings, and pass that to your function: 基本上,创建一些固定的内存来存储字符串,并将其传递给函数:

Marshal.AllocHGlobal will allocate some memory for you that you can give to your c++ function. Marshal.AllocHGlobal将为您分配一些内存,您可以将其分配给c ++函数。 See http://msdn.microsoft.com/en-us/library/s69bkh17.aspx . 请参阅http://msdn.microsoft.com/en-us/library/s69bkh17.aspx Your c++ function can accept that as a char * argument. 您的c ++函数可以将其作为char *参数接受。

Example: 例:

First, you'll need to convert your strings to one large byte[], separating each string with nulls (0x00). 首先,您需要将字符串转换为一个大字节[],并用空(0x00)分隔每个字符串。 Let's do this efficiently by allocating just one byte array. 让我们通过仅分配一个字节数组来有效地做到这一点。

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

Now, we just pass this to some memory we allocate using Marshal.AllocHGlobal 现在,我们将其传递给使用Marshal.AllocHGlobal分配的一些内存

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

Call your function here. 在这里调用您的函数。 You'll need to pass the number of strings you're giving the function too. 您还需要传递给函数的字符串数。 Once you're done, remember to free the allocated memory: 完成后,请记住释放分配的内存:

Marshal.FreeHGlobal(pointer)

HTH. HTH。

(I don't know VB, but I do know C# and how to use Google ( http://www.carlosag.net/tools/codetranslator/ ), so sorry if it's a bit off! :P) (我不了解VB,但我确实了解C#以及如何使用Google( http://www.carlosag.net/tools/codetranslator/ ),如果有点麻烦,请抱歉!:P)

This example in C# it is the same as VB.NET, and it has the declaration of C++ method, if this what you want you can use it. 在C#中,此示例与VB.NET相同,并且具有C ++方法的声明,如果需要,可以使用它。 C#: passing array of strings to a C++ DLL C#:将字符串数组传递给C ++ DLL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM