2011-09-22 39 views
0

我正在C++中編寫一個DLL,我想將一個數組傳遞給一個C#程序。我已經設法用單個變量和結構來做到這一點。也可以傳遞一個數組嗎?從C++庫傳遞數組到C#程序

我在問,因爲我知道數組在這兩種語言中以不同方式設計,我不知道如何「翻譯」它們。

在C++中我那樣做:

extern "C" __declspec(dllexport) int func(){return 1}; 

而在C#這樣的:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "func")] 
public extern static int func(); 

回答

2

使用C++/CLI將是最好,最簡單的方法。 如果你的C數組說整數,你會做這樣的:

#using <System.dll> // optional here, you could also specify this in the project settings. 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    const int count = 10; 
    int* myInts = new int[count]; 
    for (int i = 0; i < count; i++) 
    { 
     myInts[i] = i; 
    } 
    // using a basic .NET array 
    array<int>^ dnInts = gcnew array<int>(count); 
    for (int i = 0; i < count; i++) 
    { 
     dnInts[i] = myInts[i]; 
    } 

    // using a List 
    // PreAllocate memory for the list. 
    System::Collections::Generic::List<int> mylist = gcnew System::Collections::Generic::List<int>(count); 
    for (int i = 0; i < count; i++) 
    { 
     mylist.Add(myInts[i]); 
    } 

    // Otherwise just append as you go... 
    System::Collections::Generic::List<int> anotherlist = gcnew System::Collections::Generic::List<int>(); 
    for (int i = 0; i < count; i++) 
    { 
     anotherlist.Add(myInts[i]); 
    } 

    return 0; 
} 

注意,我不得不反覆數組的內容從本地複製到管理容器。然後,您可以在您的C#代碼中使用數組或列表。

1
  • 您可以編寫簡單的C++/CLI包裝爲本地C++庫。 Tutorial
  • 您可以使用平臺調用。如果只有一個數組可以通過,這肯定會更簡單。儘管做些更復雜的事情可能是不可能的(例如傳遞非平凡的對象)。 Documentation