Comment obtenir le contenu d'un tableau à partir d'une dll C ++ en C #
Je souhaite utiliser des fonctions de DLL en C ++ avec C #.
Je stocke des données de chaîne dans un vecteur.
Mon fichier C ++ contient:
#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;
}
En 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();
}
}
}
Je ne sais pas comment continuer à parcourir le tableau en c #. Je ne sais pas si l'utilisation du vecteur est optimale. si vous avez une autre solution, je suis prêt.
Veuillez aider.
Réponses
Mon moyen préféré pour passer un tableau de chaînes C ++ -> C # est d'utiliser un délégué.
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);
et alors
var lst = new List<string>();
TestReturnArrayStrings(lst.Add);
foreach (string str in lst)
{
Console.WriteLine(str);
}
Et 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());
}
}
}
Ici, le "truc" est que C # passe à C ++ un délégué à la List<string>.Add()
méthode, et C ++ "remplit" directement le C # List<>
. La mémoire gérée par C ++ reste du côté C ++, la mémoire gérée par le C # reste du côté C #. Aucun problème de propriété croisée de la mémoire. Comme vous pouvez l'imaginer, il est assez facile d'étendre le "truc" à n'importe quelle autre .Add()
méthode, comme HashSet<string>
, ou Dictionary<string, string>
.
Pour rappel, j'ai créé un github avec de nombreux exemples de marshaling entre C / C ++ et C # (à la fois .NET Framework et .NET Core / 5.0).
Une façon de le faire est d'utiliser la structure SAFEARRAY de COM telle qu'elle est prise en charge par .NET (l'allocateur .NET utilisé par P / Invoke est l'allocateur COM), y compris la plupart des sous-types associés, comme BSTR .
Ainsi, en C / C ++, vous pouvez définir ceci:
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;
}
Et en C #, vous pouvez définir ceci:
[DllImport("ProductLibrary.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern string[] GetProduct();