2013-06-30 37 views
0

想知道如何使用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++函數應該如何才能正確接收數組並將其分割回其字符串?

+0

C++/CLR?....... –

+0

本例中使用C++ – user2527738

+0

請張貼C++方法的聲明,這可以幫助其他人識別錯誤 – ahmedsafan86

回答

0

基本上,創造出一些固定的內存來存儲字符串,並傳遞給你的函數:

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)

相關問題