首页 / C# / 将矢量/数组从非托管C传递到C#
将矢量/数组从非托管C传递到C#
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将矢量/数组从非托管C传递到C#,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2284字,纯文字阅读大概需要4分钟。
内容图文
![将矢量/数组从非托管C传递到C#](/upload/InfoBanner/zyjiaocheng/711/5f398b8408b94a7dad2e008ee09afda9.jpg)
我想从非托管C传递大约100 – 10,000点到C#.
C面看起来像这样:
__declspec(dllexport) void detect_targets( char * , int , /* More arguments */ )
{
std::vector<double> id_x_y_z;
// Now what's the best way to pass this vector to C#
}
现在我的C#端看起来像这样:
using System;
using System.Runtime.InteropServices;
class HelloCpp
{
[DllImport("detector.dll")]
public static unsafe extern void detect_targets( string fn , /* More arguments */ );
static void Main()
{
detect_targets("test.png" , /* More arguments */ );
}
}
我如何改变我的代码,以便将std :: vector从非托管C传递给C#?
解决方法:
只要托管代码不调整向量大小,就可以访问缓冲区并将其作为指针传递给vector.data()(对于C 0x)或& vector [0].这导致零拷贝系统.
示例C API:
#define EXPORT extern "C" __declspec(dllexport)
typedef intptr_t ItemListHandle;
EXPORT bool GenerateItems(ItemListHandle* hItems, double** itemsFound, int* itemCount)
{
auto items = new std::vector<double>();
for (int i = 0; i < 500; i++)
{
items->push_back((double)i);
}
*hItems = reinterpret_cast<ItemListHandle>(items);
*itemsFound = items->data();
*itemCount = items->size();
return true;
}
EXPORT bool ReleaseItems(ItemListHandle hItems)
{
auto items = reinterpret_cast<std::vector<double>*>(hItems);
delete items;
return true;
}
呼叫者:
static unsafe void Main()
{
double* items;
int itemsCount;
using (GenerateItemsWrapper(out items, out itemsCount))
{
double sum = 0;
for (int i = 0; i < itemsCount; i++)
{
sum += items[i];
}
Console.WriteLine("Average is: {0}", sum / itemsCount);
}
Console.ReadLine();
}
#region wrapper
[DllImport("Win32Project1", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
static unsafe extern bool GenerateItems(out ItemsSafeHandle itemsHandle,
out double* items, out int itemCount);
[DllImport("Win32Project1", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
static unsafe extern bool ReleaseItems(IntPtr itemsHandle);
static unsafe ItemsSafeHandle GenerateItemsWrapper(out double* items, out int itemsCount)
{
ItemsSafeHandle itemsHandle;
if (!GenerateItems(out itemsHandle, out items, out itemsCount))
{
throw new InvalidOperationException();
}
return itemsHandle;
}
class ItemsSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public ItemsSafeHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return ReleaseItems(handle);
}
}
#endregion
内容总结
以上是互联网集市为您收集整理的将矢量/数组从非托管C传递到C#全部内容,希望文章能够帮你解决将矢量/数组从非托管C传递到C#所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。