将数组从c ++库传递给C#程序

时间:2011-09-22 17:41:27

标签: c# c++

我在c ++中创建一个dll,我想将一个数组传递给一个c#程序。我已经设法用单个变量和结构来做到这一点。是否也可以传递数组?

我问,因为我知道数组在这两种语言中的设计方式不同,我不知道如何“翻译”它们。

在c ++中,我这样做:

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

在c#中就像那样:

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

3 个答案:

答案 0 :(得分: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 :(得分:1)

  • 您可以为本机C ++库编写简单的C ++ / CLI包装器。 Tutorial
  • 您可以使用平台调用。如果您只有一个数组要通过,这肯定会更简单。但是做一些更复杂的事情可能是不可能的(例如传递非平凡的对象)。 Documentation

答案 2 :(得分:1)

为了将数组从C ++传递给C#,请在C ++端使用CoTaskMemAlloc系列函数。您可以在上找到有关此信息 http://msdn.microsoft.com/en-us/library/ms692727

我认为这对你的工作来说已经足够了。