0

Wondering how to use VB.NET to call a C++ function with an array as a parameter:

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. What should my C++ function look like in order to properly receive the array and split it back to its strings?

4

2 に答える 2

0

この C# の例は、VB.NET と同じで、C++ メソッドの宣言が含まれています。これが必要な場合は、それを使用できます。C#: 文字列の配列を C++ DLL に渡す

于 2013-06-30T07:28:37.560 に答える
0

基本的に、固定メモリを作成して文字列を保存し、それを関数に渡します。

Marshal.AllocHGlobalは、c++ 関数に与えることができるメモリを割り当てます。http://msdn.microsoft.com/en-us/library/s69bkh17.aspxを参照してください。C++ 関数は、それを char * 引数として受け入れることができます。

例:

まず、文字列を 1 つの大きな byte[] に変換し、各文字列をヌル (0x00) で区切る必要があります。バイト配列を1つだけ割り当てることで、これを効率的に行いましょう。

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)

于 2013-06-30T05:59:51.287 に答える