繁体   English   中英

如何传递List <int> 从C#到C ++ CLi?

[英]How to pass List<int> from C# to C++ CLi?

我是C语言家族的初学者......

所以,问题是 - 在我的解决方案中,我有一个存储List<int>的repo(用C#编写),我也有一个引擎(用C ++编写)。 所以,我需要将C#实现中的List传递给C ++ CLI来执行...

据我所知,问题是C ++知道如何使用std::vector和C#知道如何使用List ,我需要以某种方式将List转换为vector ...

怎么做?

任何适当的假设。

编辑

很抱歉误解,但我的CLI作为纯C ++实现的映射器。 因此,据我所知,从C#我需要将List传递给C ++ CLI,C ++ CLI将List转换为vector并使用纯C ++实现调用另一个C ++文件。

这是我的解决方案

h文件使用命名空间系统; using namespace System :: Collections :: Generic;

//forward declaration 
class MathCore;

namespace MathCore_CLI_namespace
{
public ref class MathCore_CLI
{
public:
    MathCore_CLI();
    ~MathCore_CLI();


    int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second);
    //int computeMulPlusVals(std::vector<int> vect_first, std::vector<int> vect_second);

private:
    MathCore * m_pMathCore;
};
}

cpp文件

#include "stdafx.h"
#include "MathCore_CLI.h"
#include "..\Engine\MathCore.h"
#include <iostream>
#include <array>
using namespace System;
using namespace System::Collections::Generic;

namespace MathCore_CLI_namespace
{
const int size = 5;
int count = 0;
int arrayVal[size];

MathCore_CLI::MathCore_CLI()
{
    m_pMathCore = new MathCore();
}

MathCore_CLI::~MathCore_CLI()
{
    delete m_pMathCore;
}



int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second)
{
    return 0;
}
}

错误

在此输入图像描述

我做错了什么?

C ++ CLI直接支持List,您不需要转换。 这是典型的签名。

private: System::Void FooMethod( System::Collections::Generic::List<Int32>^ list )

此外,在您更新的问题中,您有链接器错误。

打开C ++项目属性,查找链接器,然后输入。 将位置添加到(EngineLib_Cli.dll)库中

我还找到了更优化的解决方案

int MathCore_CLI::computeMulPlusVals(array<int>^ arr_first, array<int>^ arr_second)
{
    auto vec_first = std::vector<int>(arr_first->Length);
    cli::pin_ptr<int> pPinnedFirst = &arr_first[0];
    memcpy(vec_first.data(), pPinnedFirst, arr_first->Length * sizeof(int));

    auto vec_second = std::vector<int>(arr_second->Length);
    cli::pin_ptr<int> pPinnedSecond = &arr_second[0];
    memcpy(vec_second.data(), pPinnedSecond, arr_second->Length * sizeof(int));

    return m_pMathCore->computeMulPlusVals(vec_first, vec_second);
}

按步骤

1)你需要创建你的向量2)在堆中保存这个内存3)只需复制数据

它会更快

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM