2011-09-22 173 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