Jak pobrać zawartość tablicy z biblioteki dll w języku C ++ w języku C #
Chcę używać funkcji z biblioteki DLL w C ++ z C #.
Przechowuję dane tekstowe w wektorze.
Mój plik C ++ zawiera:
#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;
}
W 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();
}
}
}
Nie wiem, jak kontynuować przeglądanie tablicy w języku C #. Nie wiem, czy użycie wektora jest optymalne. jeśli masz inne rozwiązanie, jestem gotowy.
Proszę pomóż.
Odpowiedzi
Moim ulubionym sposobem przekazywania tablicy ciągów C ++ -> C # jest użycie delegata.
DO#:
// 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);
i wtedy
var lst = new List<string>();
TestReturnArrayStrings(lst.Add);
foreach (string str in lst)
{
Console.WriteLine(str);
}
I 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());
}
}
}
Tutaj „sztuczka” polega na tym, że C # przekazuje do C ++ delegata List<string>.Add()
metody, a C ++ „wypełnia” bezpośrednio C # List<>
. Pamięć zarządzana przez C ++ pozostaje po stronie C ++, pamięć zarządzana przez C # pozostaje po stronie C #. Żadnych problemów związanych z posiadaniem wielu pamięci. Jak możesz sobie wyobrazić, dość łatwo jest rozszerzyć tę „sztuczkę” na dowolną inną .Add()
metodę, taką jak HashSet<string>
, lub Dictionary<string, string>
.
Na marginesie, stworzyłem github z wieloma przykładami dotyczącymi organizowania między C / C ++ i C # (zarówno .NET Framework, jak i .NET Core / 5.0).
Jednym ze sposobów jest użycie struktury COM SAFEARRAY, która jest obsługiwana przez .NET (alokator .NET używany przez P / Invoke to alokator COM), w tym większość powiązanych podtypów, takich jak BSTR .
Tak więc w C / C ++ możesz to zdefiniować:
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;
}
A w C # możesz to zdefiniować:
[DllImport("ProductLibrary.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern string[] GetProduct();