C#でC ++ dllから配列のコンテンツを取得する方法
C ++のDLLの関数をC#で使用したい。
文字列データをベクトルに格納します。
私のC ++ファイルには次のものが含まれています。
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern "C" __declspec(dllexport) std::vector<std::string> GetProduct();
std::vector<std::string> GetProduct()
{
std::vector<std::string> vectProduct;
vectProduct.push_back("Citroen");
vectProduct.push_back("C5");
vectProduct.push_back("MOP-C5");
return vectProduct;
}
C#では
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
class Program
{
[DllImport("ProductLibrary.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern StringBuilder GetProduct();
static void Main(string[] args)
{
StringBuilder vectProduct_impl = GetProduct();
}
}
}
C#で配列を参照し続ける方法がわかりません。ベクトルの使用が最適かどうかはわかりません。あなたが他の解決策を持っているなら、私は準備ができています。
助けてください。
回答
文字列の配列C ++-> C#を渡すための私のお気に入りの方法は、デリゲートを使用することです。
C#:
// If possible use UnmanagedType.LPUTF8Str
// or under Windows rewrite everything to use
// wchar_t, std::wstring and UnmanagedType.LPWStr
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void AddAnsi([MarshalAs(UnmanagedType.LPStr)] string str);
[DllImport("CPlusPlusSide.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void TestReturnArrayStrings(AddAnsi add);
その後
var lst = new List<string>();
TestReturnArrayStrings(lst.Add);
foreach (string str in lst)
{
Console.WriteLine(str);
}
そしてC ++:
#include <string>
#include <vector>
extern "C"
{
__declspec(dllexport) void TestReturnArrayStrings(void (add)(const char* pstr))
{
std::string str1 = "Hello";
std::string str2 = "World";
add(str1.data());
add(str2.data());
// Example with std::vector
add("--separator--"); // You can even use C strings
std::vector<std::string> v = { "Foo", "Bar" };
// for (std::vector<std::string>::iterator it = v.begin(); it != v.end(); ++it)
for (std::vector<std::string>::const_iterator it = v.begin(); it != v.end(); ++it)
{
add(it->data());
}
add("--separator--"); // You can even use C strings
// With C++ 11
// for (auto& it: v)
for (const auto& it: v)
{
add(it.data());
}
}
}
ここでの「トリック」は、C#がList<string>.Add()
メソッドへのデリゲートをC ++に渡し、C ++がC#を直接「埋める」ことList<>
です。C ++によって管理されるメモリはC ++側に残り、C#によって管理されるメモリはC#側に残ります。クロスメモリ所有権の問題はありません。あなたが想像できるように、他に「トリック」を展開することは非常に簡単である.Add()
ように、方法HashSet<string>
、またはDictionary<string, string>
。
補足として、C / C ++とC#(。NETFrameworkと.NETCore / 5.0の両方)間のマーシャリングに関する多くの例を含むgithubを作成しました。
これを行う1つの方法は、.NETでサポートされているCOMのSAFEARRAY構造を使用することです(P / Invokeで使用される.NETアロケーターはCOMアロケーターです)。これには、BSTRなどの関連するサブタイプのほとんどが含まれます。
したがって、C / C ++では、次のように定義できます。
extern "C" __declspec(dllexport) LPSAFEARRAY GetProduct();
LPSAFEARRAY GetProduct()
{
LPSAFEARRAY psa = SafeArrayCreateVector(VT_BSTR, 0, 3);
LONG index = 0;
// _bstr_t is a smart class that frees allocated memory automatically
// it needs #include <comdef.h>
// but you can also use raw methods like SysAllocString / SysFreeString
_bstr_t s0(L"Citroen"); // could use "Citroen" if you really want ANSI strings
// note SafeArrayPutElement does a copy internally
SafeArrayPutElement(psa, &index, s0.GetBSTR());
index++;
_bstr_t s1(L"C5");
SafeArrayPutElement(psa, &index, s1.GetBSTR());
index++;
_bstr_t s2(L"MOP - C5");
SafeArrayPutElement(psa, &index, s2.GetBSTR());
index++;
return psa;
}
そしてC#では、これを定義することができます:
[DllImport("ProductLibrary.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern string[] GetProduct();