如何调用C ++函数从C#进行Vector调用

时间:2013-05-31 18:58:18

标签: c# c++ .net

我在C ++工作并创建分析数据的库。我创建了几个具有C ++向量函数的类。现在我想在C#中创建UI并调用这些类。我想创建API来从C#调用。

由于数据是数组/向量,那么如何从C#中调用它?

2 个答案:

答案 0 :(得分:0)

我本来只是发表评论,但我的代表不够高。在使用C ++的类库中使用STL类(例如向量或字符串)时会出现一些复杂情况。您可以在此处查看更多信息和可能的解决方案:I can pass std::string for a Dll and what i can do with DLL´s?

答案 1 :(得分:0)

您需要创建自己的C ++ / CLI互操作才能实现此目的。

强烈推荐一本好书,由Marcus Heege撰写的“Expert C ++ / CLI”,非常好读。

这是我的简短例子:

// Program.cs
static void Main(string[] args)
{
    List<string> someStringList = new List<string>();
    someStringList.Add("Betty");
    someStringList.Add("Davis");
    someStringList.Add("Eyes");

    NativeClassInterop nativeClass = new NativeClassInterop();
    string testString = nativeClass.StringCat(someStringList);
}

// NativeClass.h, skipping this, it's obvious anyways

// NativeClass.cpp, normal C++ class, this was in some DLL project, don't need exports
#include "stdafx.h"
#include "NativeClass.h"
std::string NativeClass::StringCat(std::vector<std::string> stringList)
{
    std::string result = "";
    for(unsigned int i = 0; i < stringList.size(); i++)
    {
        if(i != 0)
        {
            result += " ";
        }
        result += stringList[i];
    }
    return result;
}

// NativeClassInterop.cpp, in same DLL project, but compile this file with /clr switch
#include <gcroot.h>
#using <System.dll>
#include <vector>
#include <string>
#include "NativeClass.h"

// Helper method
static std::string nativeStringFromManaged(System::String^ str)
{
    System::IntPtr hGlobal =
        System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str);

    std::string nativeString((hGlobal.ToPointer() == 0) 
        ? "" : (char*)hGlobal.ToPointer());

    System::Runtime::InteropServices::Marshal::FreeHGlobal(hGlobal);
    return nativeString;
}

// C++/CLI wrapper class
public ref class NativeClassInterop
{
public:
    System::String^ StringCat(System::Collections::Generic::List<System::String^>^ someStringList)
    {
        // You get to do the marshalling for the inputs
        std::vector<std::string> stringList;
        for(int i = 0; i < someStringList->Count; i++)
        {
            stringList.push_back(nativeStringFromManaged(someStringList[i]));
        }

        NativeClass nativeClass;
        std::string nativeString = nativeClass.StringCat(stringList);

        // And for the outputs ;-)
        System::String^ managedString = gcnew System::String(nativeString.c_str());
        return managedString;
    }
};