gpt4 book ai didi

.net - 如何在 C++/CLI 程序和 C++/CLI DLL 之间传递字节数组?

转载 作者:行者123 更新时间:2023-12-05 07:57:31 26 4
gpt4 key购买 nike

我有一个 CLR DLL,用作与不同处理器类型的设备进行通信的接口(interface)。当从 C# 测试程序调用时,DLL 已经过测试并按预期工作。

在 C++/CLI 测试程序中,我无法将要放入缓冲区的值作为读取函数(在 dll 中)中的参数传递。

[更新]
这里 是我在 dll 中使用的函数的声明:

//changed pointers to arrays
bool connect(uint procType, String^ commPort);//Works as expected
bool read(uint16 addr, array<uint8>^% buf, uint bufSize, uint8 page);//data is not put into buf
bool write(uint16 addr, array<uint8>^% buf, uint bufSize, uint page);//Unknown behavior (cannot read to varify)
void close(void);//works as expected

[更新]
这里是C++/CLI测试程序:

using namespace System;
using namespace ProcessorInterfaceCLR;//namespace in dll

int main(int argc, char * argv[])
{

ProcessorCLR proc;

/* connect to device */
bool is_connected = proc.connect(1, "COM3");
if (is_connected)/* connect successful */ //Connect passes and fails when expected
{
unsigned short addr = 0x1000; //test address
const unsigned int size = 10;
array<Byte>^ buf = gcnew array<Byte>(size);// <-------- init managed array

/* read the data at the location */
bool retval = proc.read(addr, buf, size, 0/*page*/); //retval == true
//buf == {0,0,0...}, This is not the correct data

/* close comm when done */
proc.close();
}
return 0;
}

问题read()应该将字节放在缓冲区中,而是将数据放在缓冲区中全为0。

[更新]
这里是我在dll中读取函数的实现。它将托管数组转换为非托管数组,并将其传递给包装在 cli dll 中的 c++ 函数。

/*
Reads data from the device into the given buffer. */
bool ProcessorCLR::read(uint16 addr, array<uint8>^% buffer, uint size, uint8 page)
{
pin_ptr<uint8> buf = &buffer[0];
return proc->read(addr, buf, size, page);
}

我通过注释掉对 proc->read() 的调用来对此进行测试并添加 buf[0] = 1并且我能够获得返回值。 所以, 问题是数组,虽然 proc->read() 通常会更改非托管数组中的值,但它不会更改托管数组的 pin_ptr 的值大批。

问题已在上次更新中解决。我不得不将非托管阵列切换为托管阵列 添加 %指定将传递引用的运算符。

最佳答案

为了解决我的问题,我必须:

  1. 将 c++/cli dll 中的非托管数组切换为托管数组,然后使用 pin_ptr 在 dll 的内部函数中像非托管数组一样使用它们。

  2. % 运算符添加到托管数组参数以指定它们将通过引用传递。

有关详细信息,请参阅我的问题。

关于.net - 如何在 C++/CLI 程序和 C++/CLI DLL 之间传递字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26895555/

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