gpt4 book ai didi

c# - 将 vector/数组从非托管 C++ 传递到 C#

转载 作者:IT老高 更新时间:2023-10-28 21:36:33 27 4
gpt4 key购买 nike

我想将大约 100 - 10,000 点从非托管 C++ 传递到 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 */ );
}
}

我需要如何更改我的代码才能将非托管 C++ 中的 std::vector 及其所有内容传递给 C#?

最佳答案

只要托管代码不调整 vector 的大小,您就可以访问缓冲区并使用 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# - 将 vector/数组从非托管 C++ 传递到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31417688/

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