将数组从c++库传递到c#程序
Pass array from c++ library to a C# program
我正在用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
我认为这对你的工作足够了。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 显示错误输出的简单数组排序程序
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 有人可以在下面的示例 C++ 程序中解释字符数组 KCHAR1 的奇怪行为吗?
- C ++程序如何返回我的数组或写入全局变量
- For 循环在尝试读取数组 c++ 时程序崩溃
- 无法将 2D 数组传递到 c++ 中的帮助程序函数中
- 将数组作为多线程应用程序中函数的返回传递
- 该程序将.csv文件中的一系列单词放入数组中,然后随机生成句子.但它不起作用
- 我编写了一个程序来显示数组的内容,但它显示的是它的地址
- C ++程序在字符数组中插入单词
- 数组 C++ 上的异常处理程序
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 使用终止程序的指针在数组中输入字符串
- C++引物动态数组初始化程序的数目超过大小