![](/img/trans.png)
[英]How to call an unmanaged C++ function with a std::vector<>::iterator as parameter from C#?
[英]How to call C++ function takes Vector call from C#
我正在使用C ++並創建用於分析數據的庫。 我創建了一些類,這些類的功能采用C ++向量。 現在,我想用C#創建UI並調用這些類。 我正在考慮創建從C#調用的API。
由於數據是數組/向量,那么如何從C#中調用它呢?
我只想對此發表評論,但是我的代表不夠高。 在帶有C ++的類庫中使用STL類(例如向量或字符串)時,會有一些復雜性。 您可以在此處查看更多信息和可能的解決方案: 我可以將std :: string傳遞給Dll,而我可以用DLL做什么?
您需要創建自己的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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.