0

私はC++で作業しており、データを分析するライブラリを作成しています。C++ ベクトルを取る関数を持ついくつかのクラスを作成しました。C# で UI を作成し、これらのクラスを呼び出したいと思います。C#から呼び出すAPIを作ろうと思っています。

データは配列/ベクトルなので、C# からどのように呼び出すことができますか?

4

2 に答える 2

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;
    }
};
于 2013-05-31T20:39:27.137 に答える
0

私はこれをコメントしただけですが、私の担当者は十分に高くありません. C++ のクラス ライブラリで STL クラス (ベクトルや文字列など) を使用する場合、いくつかの複雑な問題があります。いくつかの詳細情報と考えられる解決策については、こちらを確認してください。DLL に std::string を渡すことができます。DLL で何ができますか?

于 2013-05-31T19:21:50.580 に答える