gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:28:42 33 4
gpt4 key购买 nike

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

请注意,我必须以迭代方式将数组的内容从 native 复制到托管容器。然后,您可以在 C# 代码中随意使用数组或列表。

关于c# - 将数组从 C++ 库传递到 C# 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519094/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com