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

Pass array from c++ library to a C# program

本文关键字:程序 数组 c++      更新时间:2023-10-16

我正在用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();

使用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#代码中任意使用数组或列表

  • 您可以为本机c++库编写简单的c++/CLI包装器。教程。
  • 可以使用平台调用。如果只有一个数组要传递,这肯定会更简单。然而,做一些更复杂的事情可能是不可能的(比如传递重要的对象)。文档。

为了将数组从c++传递到c#,在c++端使用CoTaskMemAlloc系列函数。你可以在http://msdn.microsoft.com/en-us/library/ms692727

我认为这对你的工作足够了。